最大子数组和

给你一个整数数组 nums ,请你找出一个具有最大和的连续子数组(子数组最少包含一个元素),返回其最大和。

子数组 是数组中的一个连续部分。

const maxSubArray = (nums = [-2,1,-3,4,-1,2,1,-5,4]) => {
    const length = nums.length
    if(length === 1) return nums[0]
    let pre = nums[0], max = nums[0];
    for(let i = 1; i < length;i++){
        pre = Math.max(pre + nums[i], nums[i]);
        max = Math.max(max, pre);
    }
    return max
};

  Leecode 提交通过

posted @ 2023-02-01 22:49  671_MrSix  阅读(9)  评论(0编辑  收藏  举报