# #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.

##### 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) ?

Mycode（AC = 33ms）：

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) {
if (nums.size() <= 1) return 0;

vector<int> left_max(nums), right_max(nums);

// get max for subarray indexed 0...i
int local = nums[0];
for (int i = 1; i < nums.size(); i++) {
local = max(local + nums[i], nums[i]);
left_max[i] = max(left_max[i - 1], local);
}

// get max for subarray indexed i...nums.size() - 1
local = nums[nums.size() - 1];
for (int i = nums.size() - 2; i >= 0; i--) {
local = max(local + nums[i], nums[i]);
right_max[i] = max(right_max[i + 1], local);
}

// get final result
int global = INT_MIN;
for (int i = 1; i < nums.size(); i++) {
global = max(global, left_max[i - 1] + right_max[i]);
}
return global;
}
};


#### 718. Maximum Length of Repeated Subarray

2017-11-02 08:44:26

#### Array-Maximum Length of Repeated Subarray

2017-12-09 22:03:57

#### A + B Problem II

2018-01-23 19:22:15

#### HDU 3818 A + B Problem 简单数论题

2012-09-05 18:17:37

#### 杭电acm:1002 A+B Problem 2

2018-03-26 13:42:51

#### A+B problem （压8位高精度加法模板）

2018-02-28 10:39:24

#### Problem A+B(Big Integer)大数相加

2016-02-26 14:52:19

#### hdu A+B

2016-11-25 07:41:02

#### 杭电ACM 1002:A+B Problem II

2015-04-07 22:27:54

#### Lintcode A+B问题

2016-07-20 08:25:59