# LeetCode Maximum Subarray

LeetCode Maximum Subarray

Find the contiguous subarray within an array (containing at least one number) which has the largest sum.

For example, given the array [-2,1,-3,4,-1,2,1,-5,4],
the contiguous subarray [4,-1,2,1] has the largest sum = 6.

More practice: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);
}
};