Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Create MaximumSubarrayII.h #23

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
53 changes: 53 additions & 0 deletions MaximumSubarrayII.h
Original file line number Diff line number Diff line change
@@ -0,0 +1,53 @@
/*
2015-09-13
bluepp
May the force be with me!

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

Have you met this question in a real interview? Yes
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.
http://www.lintcode.com/en/problem/maximum-subarray-ii/#
*/

int maxTwoSubArrays(vector<int> nums) {
// write your code here
int n = nums.size();

int sum1 = 0, maxsum1 = INT_MIN;
int dp1[n];
memset(dp1, 0, sizeof(dp1));

for(int i = 0; i < n; i++)
{
sum1 = max(sum1+nums[i], nums[i]);
maxsum1 = max(maxsum1, sum1);
dp1[i] = maxsum1;
}

int dp2[n];
memset(dp2, 0, sizeof(dp2));
dp2[n-1] = nums[n-1];;
int sum2 = 0, maxsum2 = INT_MIN;
for (int i = n-1; i >= 0; i--)
{
sum2 = max(nums[i], sum2+nums[i]);
maxsum2 = max(maxsum2, sum2);
dp2[i] = maxsum2;
}

int ret = INT_MIN;
for (int i = 0; i < n-1; i++)
{
ret = max(ret, dp1[i] + dp2[i+1]);
}

return ret;
}