连续子数组的最大和

83 阅读1分钟

连续子数组的最大和

描述

输入一个整型数组,数组中的一个或连续多个整数组成一个子数组。求所有子数组的和的最大值。

示例

输入: nums = [-2,1,-3,4,-1,2,1,-5,4]
输出: 6
解释: 连续子数组 [4,-1,2,1] 的和最大,为 6。

解法

/**
 * @param {number[]} nums
 * @return {number}
 */
//  动态规划
var maxSubArray = function(nums) {
    let max=nums[0];
    let res=nums[0];
    for(let i=1;i<nums.length;i++){
        let temp=Math.max(res+nums[i],nums[i])
        res=temp;
        max=Math.max(res,max);
    }
    return max;
};