题目链接:Maximum Subarray
- 题目描述:
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.
(1)思路:参考以下,Kadane算法。
最大子串和问题
清晰解题: 寻找最大子数列-Kadane算法
连续子数组最大和
从数组头循环,使用两个计数变量sum和max分别记录当前扫描和以及已扫描的最大和,当sum为负时重置为0。
(2)代码:
class Solution {
public:
int maxSubArray(vector<int>& nums) {
if (nums.size() < 1) return 0;
int i, sum = 0;
int max = nums[0];
for (i = 0; i < nums.size(); ++i) {
sum += nums[i];
if (sum > max) max = sum;
if (sum < 0) sum = 0;
}
return max;
}
};