-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathmaximumSubarray.cpp
More file actions
68 lines (55 loc) · 1.81 KB
/
Copy pathmaximumSubarray.cpp
File metadata and controls
68 lines (55 loc) · 1.81 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
// Source : https://leetcode.com/problems/maximum-subarray/
// Author : weekend27
// Date : 2015-12-20
/**********************************************************************************
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.
click to show more practice.
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.
**********************************************************************************/
// How to do it:
// divide and conquer
/*
subarray A[i,..j] is
(1) Entirely in A[low,mid-1]
(2) Entirely in A[mid+1,high]
(3) Across mid
*/
class Solution {
public:
int maxSubArray(vector<int>& nums) {
int n = nums.size();
int maxV = INT_MIN;
return maxArray(nums, 0, n-1, maxV);
}
int maxArray(vector<int>& nums, int left, int right, int& maxV){
if (left > right){
return INT_MIN;
}
int mid = left + (right - left) / 2;
int lmax = maxArray(nums, left, mid-1, maxV);
int rmax = maxArray(nums, mid+1, right, maxV);
maxV = max(lmax, maxV);
maxV = max(rmax, maxV);
int lsum = 0;
int mlmax = 0;
for (int i = mid-1; i >= left; i--){
lsum += nums[i];
if (lsum > mlmax){
mlmax = lsum;
}
}
int rsum = 0;
int mrmax = 0;
for (int i = mid+1; i <= right; i++){
rsum += nums[i];
if (rsum > mrmax){
mrmax = rsum;
}
}
maxV = max(maxV, mlmax + mrmax + nums[mid]);
return maxV;
}
};