# LeetCode Maximum Subarray

Given an integer array nums, find the contiguous subarray (containing at least one number) which has the largest sum and return its sum.

Example:

Input: [-2,1,-3,4,-1,2,1,-5,4],
Output: 6
Explanation: [4,-1,2,1] has the largest sum = 6.


If you have figured out the O(n) solution, try coding another solution using the divide and conquer approach, which is more subtle.

class Solution {
public:
int maxSubArray(vector<int>& nums)
{
vector<int> dp(nums.size(), 0);
dp[0] = nums[0];
int ans = nums[0];
for (int i = 1; i < nums.size(); i++) {
if (dp[i – 1] > 0)
dp[i] = dp[i – 1] + nums[i];
else
dp[i] = nums[i];
if (dp[i] > ans)
ans = dp[i];
}
return ans;
}
};

class Solution {
public:
int divide(vector<int>& nums, int left, int right)
{
if (left == right)
return nums[left];
if (left == right – 1)
return max(nums[left] + nums[right], max(nums[left], nums[right]));
int mid = (left + right) / 2;
int lmax = divide(nums, left, mid – 1);
int rmax = divide(nums, mid + 1, right);
int mmax = nums[mid], tmp = nums[mid];
for (int i = mid – 1; i >= left; i–) {
tmp += nums[i];
if (tmp > mmax)
mmax = tmp;
}
tmp = mmax;
for (int i = mid + 1; i <= right; i++) {
tmp += nums[i];
if (tmp > mmax)
mmax = tmp;
}
return max(mmax, max(lmax, rmax));
}
int maxSubArray(vector<int>& nums) { return divide(nums, 0, nums.size() – 1); }
};

class Solution {
public:
int maxSubArray(vector<int>& nums) {
int n = nums.size();
int max_sum = INT_MIN, cur_sum = 0;
for (int i = 0; i < n; ++i) {
if (cur_sum >= 0) {
cur_sum += nums[i];
}
else {
cur_sum = nums[i];
}
max_sum = max(max_sum, cur_sum);
}
return max_sum;
}
};