forked from lzl124631x/LeetCode
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy paths5.cpp
More file actions
27 lines (26 loc) · 896 Bytes
/
s5.cpp
File metadata and controls
27 lines (26 loc) · 896 Bytes
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
// OJ: https://leetcode.com/problems/maximum-subarray/
// Author: github.com/lzl124631x
// Time: O(NlogN)
// Space: O(logN)
class Solution {
private:
int crossSum(vector<int>& nums, int L, int R, int p) {
if (L == R) return nums[L];
int left = INT_MIN, right = INT_MIN, i, sum;
for (i = p, sum = 0; i >= L; --i) left = max(left, sum += nums[i]);
for (i = p + 1, sum = 0; i <= R; ++i) right = max(right, sum += nums[i]);
return left + right;
}
int helper(vector<int>& nums, int L, int R) {
if (L == R) return nums[L];
int p = (L + R) / 2;
int left = helper(nums, L, p);
int right = helper(nums, p + 1, R);
int cross = crossSum(nums, L, R, p);
return max(left, max(right, cross));
}
public:
int maxSubArray(vector<int>& nums) {
return helper(nums, 0, nums.size() - 1);
}
};