美文网首页
53. Maximum Subarray

53. Maximum Subarray

作者: Icytail | 来源:发表于2017-11-08 16:58 被阅读0次

    Description:

    Find the contiguous subarray within an array (containing at least one number) which has the largest sum.

    For example, given the array[-2,1,-3,4,-1,2,1,-5,4],the contiguous subarray[4,-1,2,1]has the largest sum =6.

    click to show more practice.

    My code:

    /**
     * @param {number[]} nums
     * @return {number}
     */
    var maxSubArray = function(nums) {
        let max = nums[0];
        for(let i = 0; i < nums.length; i++) {
            let sum = 0;
            for(let j = i; j < nums.length; j++) {
                sum += nums[j];
                if(max < sum) {
                    max = sum;
                }
            }
        }
        return max;
    };
    

    Note: 需要注意数组中只有负数的情况,不能直接赋初始max为0

    相关文章

      网友评论

          本文标题:53. Maximum Subarray

          本文链接:https://www.haomeiwen.com/subject/nnsymxtx.html