LeetCode maximum-subarray

给定一个整数数组 nums ,找到一个具有最大和的连续子数组(子数组最少包含一个元素),返回其最大和。 示例:

输入: [-2,1,-3,4,-1,2,1,-5,4], 输出: 6 解释: 连续子数组 [4,-1,2,1] 的和最大,为 6。

进阶:

如果你已经实现复杂度为 O(n) 的解法,尝试使用更为精妙的分治法求解。

解答:

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
class Solution {
public:
int maxSubArray1(vector<int>& nums) {
int res = nums[0], sum = 0;
for(int num : nums) {
if (sum > 0) // sum + nums[i] > nums[i]
sum += num;
else
sum = num;
res = max(sum, res);
}
return res;
}

int maxSubArray2(vector<int>& nums) {
if (nums.size() == 0)
return 0;
return __maxSubArray(nums, 0, nums.size() - 1);
}

int __maxSubArray(vector<int> &nums, int left, int right) {
if (left == right)
return nums[left];
int mid = (left + right) >> 1;
int lsum = __maxSubArray(nums, 0, mid);
int rsum = __maxSubArray(nums, mid + 1, right);

int maxLeftBorderSum = INT_MIN, leftBorderSum = 0;
for (int i = mid; i >= left; i--) {
leftBorderSum += nums[i];
if (leftBorderSum > maxLeftBorderSum)
maxLeftBorderSum = leftBorderSum;
}

int maxRightBorderSum = INT_MIN, rightBorderSum = 0;
for (int j = mid + 1; j <right; j++) {
rightBorderSum += nums[j];
if (rightBorderSum > maxRightBorderSum)
maxRightBorderSum = rightBorderSum;
}

return max(max(lsum, rsum), maxLeftBorderSum + maxRightBorderSum);
}
};

Comments

Your browser is out-of-date!

Update your browser to view this website correctly. Update my browser now

×