Given an array of integers, find two non-overlapping subarrays which have the largest sum.
The number in each subarray should be contiguous.
Return the largest sum.
Note
The subarray should contain at least one number
Example
思路和股票买卖III一样:
For given [1, 3, -1, 2, -1, 2], the two subarrays are [1, 3] and [2, -1, 2] or [1, 3, -1, 2] and [2], they both have the largest sum 7.
分层两段,左边和右边分别计算max subarray,然后两边加起来最大的就是结果。
这道题目里没有明确说一定要两段(比如一段可不可以,比如左边没有值,右边有一段),但是实际结果是一段是不可以的。。。
public int maxTwoSubArrays(ArrayList<Integer> nums) {
int[] left = new int[nums.size()];
int localMax = 0;
int globalMax = Integer.MIN_VALUE;
for (int i = 0; i < nums.size(); i++) {
localMax = Math.max(nums.get(i), localMax + nums.get(i));
globalMax = Math.max(localMax, globalMax);
left[i] = globalMax;
}
localMax = 0;
globalMax = Integer.MIN_VALUE;
int result = Integer.MIN_VALUE;
for (int i = nums.size()-1; i >= 0; i--) {
if (i < nums.size()-1) {
result = Math.max(result, left[i] + globalMax);
}
localMax = Math.max(nums.get(i), localMax + nums.get(i));
globalMax = Math.max(localMax, globalMax);
}
return result;
}