參與活動得徽章 juejin.cn/topic/68247…數組
給定一個整數數組
nums
,找到一個具備最大和的連續子數組(子數組最少包含一個元素),返回其最大和。markdown
const nums = [-2, 1, -3, 4, -1, 2, 1, -5, 4]
function maxSubArray (nums) {
let pre = 0, maxAns = nums[0];
nums.forEach((x) => {
pre = Math.max(pre + x, x);
maxAns = Math.max(maxAns, pre);
});
return maxAns;
}
複製代碼
maxAns
, 遍歷時,拿maxAns
和當前值x
比較, 保留較大的值。pre
, 和當前值x
比較, 保留較大的值, 更新 pre
。pre
的最大值, 最後返回其結果。