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],然后分别求两个子数组中的最大子段和,然后求和的最大值即可。

 1 public class Solution {
 2     /**
 3      * @param nums: A list of integers
 4      * @return: An integer denotes the sum of max two non-overlapping subarrays
 5      */
 6     public int maxTwoSubArrays(ArrayList<Integer> nums) {
 7         // write your code
 8         if (nums==null || nums.size()==0) return 0;
 9         int len = nums.size();
10         int lLocal = nums.get(0);
11         int[] lGlobal = new int[len];
12         lGlobal[0] = lLocal;
13         for (int i=1; i<len; i++) {
14             lLocal = Math.max(lLocal+nums.get(i), nums.get(i));
15             lGlobal[i] = Math.max(lLocal, lGlobal[i-1]);
16         }
17         
18         int rLocal = nums.get(len-1);
19         int[] rGlobal = new int[len];
20         rGlobal[len-1] = rLocal;
21         for (int i=len-2; i>=0; i--) {
22             rLocal = Math.max(rLocal+nums.get(i), nums.get(i));
23             rGlobal[i] = Math.max(rLocal, rGlobal[i+1]);
24         }
25         
26         int res = Integer.MIN_VALUE;
27         for (int k=0; k<len-1; k++) {
28             if (res < lGlobal[k]+rGlobal[k+1]) 
29                 res = lGlobal[k] + rGlobal[k+1];
30         }
31         return res;
32     }
33 }
原文地址:https://www.cnblogs.com/EdwardLiu/p/4336963.html