Lintcode: Maximum Subarray II

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
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. Challenge
Can you do it in time complexity O(n) ?

思路:把数组分成两部分,可以从i和i+1(0<=  i < len-1)之间分开,a[0, i] a[i+1, len-1],然后分别求两个子数组中的最大子段和,然后求和的最大值即可。

 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) {
// write your code
if (nums==null || nums.size()==0) return 0;
int len = nums.size();
int lLocal = nums.get(0);
int[] lGlobal = new int[len];
lGlobal[0] = lLocal;
for (int i=1; i<len; i++) {
lLocal = Math.max(lLocal+nums.get(i), nums.get(i));
lGlobal[i] = Math.max(lLocal, lGlobal[i-1]);
} int rLocal = nums.get(len-1);
int[] rGlobal = new int[len];
rGlobal[len-1] = rLocal;
for (int i=len-2; i>=0; i--) {
rLocal = Math.max(rLocal+nums.get(i), nums.get(i));
rGlobal[i] = Math.max(rLocal, rGlobal[i+1]);
} int res = Integer.MIN_VALUE;
for (int k=0; k<len-1; k++) {
if (res < lGlobal[k]+rGlobal[k+1])
res = lGlobal[k] + rGlobal[k+1];
}
return res;
}
}
上一篇:Gtk-WARNING **: cannot open display: :0.0


下一篇:python之operator模块