首先假设存在正数
最大子序列必然由正数开头,因为若一个子序列由前有N个负数,则从N+1位开始同一结尾的子序列必然大于前者。
负值不可能为最大加和。当当前和小于0时,重置当前和。
若不存在正数,上述方法依然有效,但注意将max与now的比较置于now重置之前,获取最小负数/零。
时间复杂度:O(N)
C++代码:
class Solution {
public:
int maxSubArray(vector<int>& nums) {
int max = *nums.begin(), now = 0;
auto it = nums.begin();
while (it != nums.end())
{
now += *it;
if (now > max)
max = now;
if (now < 0)
now = 0;
it++;
}
return max;
}
};