原题链接在这里:http://www.lintcode.com/en/problem/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.
Notice
The subarray should contain at least one number
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
.
题解:
是Maximum Subarray的进阶版.
可以建立left 保存从左向右 时 到i的最大subarray. right保存从右向左时的到i的最大subarray.
最后res 始终用left[i] + right[i+1]来保持最大.
Time Complexity: O(n). Space: O(n).
AC Java:
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 if(nums == null || nums.size() == 0){ 8 return 0; 9 } 10 11 int n = nums.size(); 12 int [] left = new int[n]; 13 int local = 0; 14 int global = Integer.MIN_VALUE; 15 for(int i = 0; i<n; i++){ 16 local = Math.max(local + nums.get(i), nums.get(i)); 17 global = Math.max(global, local); 18 left[i] = global; 19 } 20 21 int [] right = new int[n]; 22 local = 0; 23 global = Integer.MIN_VALUE; 24 for(int i = n-1; i>=0; i--){ 25 local = Math.max(local + nums.get(i), nums.get(i)); 26 global = Math.max(global, local); 27 right[i] = global; 28 } 29 30 int res = Integer.MIN_VALUE; 31 for(int i = 0; i<n-1; i++){ 32 res = Math.max(res, left[i] + right[i+1]); 33 } 34 return res; 35 } 36 }