Skip to content

Commit 4410ee2

Browse files
committed
Create MaximumSubarrayII.h
1 parent 6109e6b commit 4410ee2

File tree

1 file changed

+53
-0
lines changed

1 file changed

+53
-0
lines changed

MaximumSubarrayII.h

Lines changed: 53 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,53 @@
1+
/*
2+
2015-09-13
3+
bluepp
4+
May the force be with me!
5+
6+
LintCode
7+
Given an array of integers, find two non-overlapping subarrays which have the largest sum.
8+
9+
The number in each subarray should be contiguous.
10+
11+
Return the largest sum.
12+
13+
Have you met this question in a real interview? Yes
14+
Example
15+
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],
16+
they both have the largest sum 7.
17+
http://www.lintcode.com/en/problem/maximum-subarray-ii/#
18+
*/
19+
20+
int maxTwoSubArrays(vector<int> nums) {
21+
// write your code here
22+
int n = nums.size();
23+
24+
int sum1 = 0, maxsum1 = INT_MIN;
25+
int dp1[n];
26+
memset(dp1, 0, sizeof(dp1));
27+
28+
for(int i = 0; i < n; i++)
29+
{
30+
sum1 = max(sum1+nums[i], nums[i]);
31+
maxsum1 = max(maxsum1, sum1);
32+
dp1[i] = maxsum1;
33+
}
34+
35+
int dp2[n];
36+
memset(dp2, 0, sizeof(dp2));
37+
dp2[n-1] = nums[n-1];;
38+
int sum2 = 0, maxsum2 = INT_MIN;
39+
for (int i = n-1; i >= 0; i--)
40+
{
41+
sum2 = max(nums[i], sum2+nums[i]);
42+
maxsum2 = max(maxsum2, sum2);
43+
dp2[i] = maxsum2;
44+
}
45+
46+
int ret = INT_MIN;
47+
for (int i = 0; i < n-1; i++)
48+
{
49+
ret = max(ret, dp1[i] + dp2[i+1]);
50+
}
51+
52+
return ret;
53+
}

0 commit comments

Comments
 (0)