LintCode 41. The largest sub-array JavaScript algorithm

description

Given an integer array, find a sub-array with the largest sum, and return its largest sum.

Description

The sub-array contains at least one number

Sample

- 样例1:

输入:[2,2,3,4,1,2,1,5,3]
输出:6
解释:符合要求的子数组为[4,1,2,1],其最大和为 6- 样例2:

输入:[1,2,3,4]
输出:10
解释:符合要求的子数组为[1,2,3,4],其最大和为 10

challenge

The required time complexity is O(n)

Parsing

const maxSubArray = function (nums) {
    
    
    if (nums === null || nums.length === 0) {
    
    
        return 0;
    }
    var maxSum = nums[0], minSum = 0, sum = 0;
    var i;
    for (i = 0; i < nums.length; i++) {
    
    
        sum += nums[i];
        if (sum - minSum > maxSum) {
    
    
            maxSum = sum - minSum;
        }
        if (sum < minSum) {
    
    
            minSum = sum;
        }
    }
    return maxSum;
}

operation result

Insert picture description here

Guess you like

Origin blog.csdn.net/SmallTeddy/article/details/108724397