参与活动得徽章 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
的最大值, 最后返回其结果。