题目:
Given an integer array
nums
, find the contiguous subarray (containing at least one number) which has the largest sum and return its sum.
找到拥有最大的和的连续的子数组
//也可以用smax = max(smax,sum);
class Solution {
public:
int maxSubArray(vector<int>& nums) {
int sum = 0, smax = INT_MIN;
//迭代器遍历数组
for (int num : nums) {
sum += num;
//如果当前的和比保存的最大值大,那就替换
if (sum > smax) smax = sum;
if (sum < 0) sum = 0;
}
return smax;
}
};