# #42 Maximum Subarray II

53人阅读 评论(0)

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;
}
};


0
0

* 以上用户言论只代表其个人观点，不代表CSDN网站的观点或立场
个人资料
• 访问：12393次
• 积分：2244
• 等级：
• 排名：第16803名
• 原创：221篇
• 转载：1篇
• 译文：0篇
• 评论：10条
文章分类
文章存档
阅读排行
评论排行