Leetcode 53, Maximum Subarray, 难度 easy
仍然是用的分治,把一个数组拆成两半,这样就有了三种情况,有可能在左边,也有可能在右边,有可能是左右两边加上中间,返回的时候有三种情况加以判断,从中间开始往两边进行遍历。
以下是代码:
class Solution {
public:
int maxSubArray(vector<int>& nums) {
return maximum(nums, 0, nums.size() - 1);
}
int maximum(vector<int>& nums, int begin, int end) {
if(begin == end) return nums[begin];
if(begin < end) {
int mid = begin + (end - begin) / 2;
int left = maximum(nums, begin, mid);
int right = maximum(nums, mid + 1, end);
int i, sum, lm = 0, rm = 0;
for (i = mid - 1, sum = 0; i >= begin; i--) {
sum += nums[i];
lm = max(sum, lm);
}
for (i = mid + 1, sum = 0; i <= end; i++) {
sum += nums[i];
rm = max(sum, rm);
}
return max(lm + nums[mid] + rm, max(left, right));
}
}
};