42. 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.
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) ?
class Solution {
public:
/*
* @param nums: A list of integers
* @return: An integer denotes the sum of max two non-overlapping subarrays
*/
int maxTwoSubArrays(vector<int> &nums) {
// write your code here
int left[nums.size()];int right[nums.size()];
int leftMax = nums.at(0); int leftSum = nums.at(0);
left[0]= nums.at(0);
for(int i = 1;i<nums.size();i++){
if(leftSum<0)
leftSum = 0;
leftSum += nums.at(i);
if(leftMax<leftSum)
leftMax = leftSum;
left[i] = leftMax;
}
int rightMax = nums.at(nums.size()-1); int rightSum = nums.at(nums.size()-1);
right[nums.size()-1]=nums.at(nums.size()-1);
for(int i = nums.size()-2;i>=0;i--){
if(rightSum<0)
rightSum = 0;
rightSum += nums.at(i);
if(rightMax<rightSum)
rightMax = rightSum;
right[i]=rightMax;
}
int Max = left[0]+right[1];
for(int j = 1;j<nums.size()-1;j++){
if(Max < left[j]+right[j+1])
Max = left[j]+right[j+1];
}
return Max;
}
};
刚开始用vector存储left和right两个数组,发现不能在特定位置插入数据,故舍弃;
用空间换时间