[LeetCode] 53. Maximum Subarray
题目链接:传送门
Description
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
.
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.
Solution
题意:
给定一个序列,求一个连续子序列使得该连续子序列的和最大
思路:
想想似乎是当时算法课上的一个经典题了,\(O(n^3)\),\(O(n^2)\),\(O(n)\)
class Solution {
public:
int maxSubArray(vector<int>& nums) {
int res = nums[0], sum = 0;
for (int i = 0; i < nums.size(); i++) {
sum = max(sum, 0);
sum += nums[i];
res = max(res, sum);
}
return res;
}
};