53. 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
.
class Solution {
2
public:
3
int divide(vector<int>& nums, int s, int e) {
4
if (s == e) return nums[s];
5
int maxa, maxb, maxc, max;
6
maxa = divide(nums, s, (s+e)/2);
7
maxb = divide(nums, (s+e)/2+1, e);
8
max = maxa > maxb ? maxa : maxb;
9
int ma = INT_MIN, mb = INT_MIN;
10
for (int i = (s+e)/2, sa = 0; i >= s; i--) {
11
sa += nums[i]; ma = ma > sa ? ma : sa;
12
}
13
for (int i = (s+e)/2+1, sb = 0; i <= e; i++) {
14
sb += nums[i]; mb = mb > sb ? mb : sb;
15
}
16
maxc = ma+mb;
17
max = max > maxc ? max : maxc;
18
return max;
19
}
20
int maxSubArray(vector<int>& nums) {
21
return divide(nums, 0, nums.size()-1);
22
}
23
};