Given an array of integers, find two non-overlapping subarrays which have the largest sum.
The number in each subarray should be contiguous.
分析:与最大子数组I问题类似。
The number in each subarray should be contiguous.
Return the largest sum.
Example
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
.
public class Solution {
/**
* @param nums: A list of integers
* @return: An integer denotes the sum of max two non-overlapping subarrays
*/
public int maxTwoSubArrays(ArrayList<Integer> nums) {
int[] leftMax = new int[nums.size()];
int max = 0;
for(int i = 0; i < nums.size(); i++) {
max = Math.max(nums.get(i), nums.get(i) + max);
if(i == 0) leftMax[i] = max;
else leftMax[i] = Math.max(leftMax[i - 1], max);
}
int res = Integer.MIN_VALUE;
max = 0;
for(int i = nums.size() - 1; i > 0; i--) {
max = Math.max(nums.get(i), nums.get(i) + max);
res = Math.max(res, max + leftMax[i - 1]);
}
return res;
}
}