LintCode Maximum Subarray II

原题链接在这里: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

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.

题解:

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 }

 

转载于:https://www.cnblogs.com/Dylan-Java-NYC/p/6406168.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值