题目
返回数组中最大的累加和以及最大累加和的元素个数
- 通过一个 current 记录当前遍历到的元素累加和
- 如果累加和>0,继续遍历下一个,判断更新累加和最大值
- 如果累加和<0,current=0,然后继续遍历后续元素,判断更新累加和
- 因为当 current 代表的累加和 <0 时,说明后面的子串+前面的一定小于后面的子串自身,所以最大累加和以及满足最大个数一定不是当前累加和+后面的子串,需要从累加和小于0的那个点之后的点开始重新计算并判断最大累加和
function process(arr) {
let max = -Infinity,
maxCount = 0;
let current = 0,
count = 0;
for (let i = 0; i < arr.length; i++) {
current += arr[i];
max = Math.max(max, current);
if (current < 0) {
count = 0;
current = 0;
} else {
count++;
maxCount = Math.max(count, maxCount);
}
}
return [max, maxCount];
}