题目描述
给定一个数组arr,返回子数组的最大累加和
例如,arr = [1, -2, 3, 5, -2, 6, -1],所有子数组中,[3, 5, -2, 6]可以累加出最大的和12,所以返回12.
[要求]
时间复杂度为O(n),空间复杂度为O(1)
输入
[1, -2, 3, 5, -2, 6, -1]
输出
12
思路
扫一遍所有数字,同时记录当前的累加和ans,如果累加和小于0了就置回0,如果累加和比当前记录的最大结果nowmax要大就更新nowmax。
只扫了一遍,且只做简单操作,所以时间复杂度O(n),只使用了两个额外变量,额外空间与数据规模无关,因此空间复杂度为O(1)。
class Solution {
public:
int maxsumofSubarray(vector<int>& arr) {
// write code here
int ans=0,nowmax=0;
for(auto i:arr){
ans+=i;
if(ans<0)
ans=0;
else if(ans>nowmax)
nowmax=ans;
}
return nowmax;
}
};