Maximum Subarray 解題報告
阿新 • • 發佈:2018-12-27
Maximum Subarray
Description
Given an array of integers, find a contiguous subarray which has the largest sum.
Notice
The subarray should contain at least one number.
Example
Given the array [−2,2,−3,4,−1,2,1,−5,3], the contiguous subarray [4,−1,2,1] has the largest sum = 6.
Challenge
Can you do it in time complexity O(n)?
實現思路
要求解陣列的最大連續子陣列,我們可以基於動態規劃的思路去思考,
對於陣列前k(1…陣列長度)項的最大連續子陣列和,只有兩種情況:
1. 包含最後一項,加上最後一項為最大
2. 不包含最後一項,前面已求得
對於1、2,分別對應了一個區域性最大值和全域性最大值,即假設我在求索引到陣列第i項的最大子陣列和,區域性最大值涵括子陣列的第i-1項,全域性最大值則不一定包括子陣列的第i-1項,但它是前面陣列中的最大子陣列和。
在求解到陣列第i項數的區域性最大值和最小值,根據定義:
1. 區域性最小值local[i] = Math.max(local[i-1]+nums[i],nums[i])
2. 全域性最大值
global[i] = Math.max(global[i-1],local[i])
通過一遍求解,global[nums.length-1]就是我們整個陣列的最大連續子陣列和。
在整個求解過程中,local和global的第i項只和第i-1項有關,所以我們可以簡化local、global成兩個數,具體實現如下所示:
public class Solution {
/**
* @param nums: A list of integers
* @return: A integer indicate the sum of max subarray
*/
public int maxSubArray(int[] nums) {
int length = nums.length;
if(length == 0){
return 0;
}
int local = nums[0],global = nums[0];
for(int i = 1;i < length; i ++){
local = Math.max(local + nums[i], nums[i]);
global = Math.max(global, local);
}
return global;
}
}