您的位置:首页 > 其它

lintcode-medium-Maximum Subarray II

2016-03-30 13:04 381 查看
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
.

Challenge

Can you do it in time complexity O(n) ?

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 size = nums.size();

int sum = nums.get(0);
int[] l2r = new int[size];
int[] r2l = new int[size];
l2r[0] = nums.get(0);
r2l[size - 1] = nums.get(size - 1);

for(int i = 1; i < size; i++){
if(sum < 0)
sum = 0;

sum += nums.get(i);

if(sum > l2r[i - 1])
l2r[i] = sum;
else
l2r[i] = l2r[i - 1];
}

sum = nums.get(size - 1);

for(int i = size - 2; i >= 0; i--){
if(sum < 0)
sum = 0;

sum += nums.get(i);

if(sum > r2l[i + 1])
r2l[i] = sum;
else
r2l[i] = r2l[i + 1];
}

int result = Integer.MIN_VALUE;

for(int i = 0; i < size - 1; i++)
result = Math.max(result, l2r[i] + r2l[i + 1]);

return result;
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: