难度:easy
1.题目描述
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.
2.算法分析
注:参考《剑指offer》
举例:输入的数组是{1,-2,3,10,-4,7,2,-5},首先sum初始化为1, 1+(-2) =
-1,当子数组{1,-2}加上后面的数字时只会减小总和,所以舍弃,sum从3开,3+10=13,当加上-4时,变成了9,此时<13,所以需要将13存储起来,因为再加上7的时候16就超过了13,所以前面存储的最大和改为16,接下来是同样的思想,知道遍历完整个数组。
3.代码实现
#include <iostream>
#include <vector>
using namespace std;
int maxSubArray(vector<int>& nums);
int main() {
int n;
int value;
vector<int> data;
cout << "the length of the array: ";
cin >> n;
for (int i = 0; i < n; ++i) {
cin >> value;
data.push_back(value);
}
cout << maxSubArray(data) << endl;
return 0;
}
// -2,1,-3,4,-1,2,1,-5,4
// output: 6
int maxSubArray(vector<int>& nums) {
int n = nums.size();
if (n == 0) return 0;
int sum = nums[0];
int greatestSum = sum;
for (int i = 1; i < n; ++i) {
if (sum > 0) {
sum += nums[i];
} else {
sum = nums[i];
}
// need to save the greatest sum because when sum > 0 you may add some negative number and make it smaller
if (sum > greatestSum) {
greatestSum = sum;
}
}
return greatestSum;
}
4.小结
主要注意一下当加上一个负数的时候需要将前面的最大值存储起来即可,这道题目比较简单,算法的时间复杂度是O(n).