js Find the maximum sum of consecutive subarrays of the A array

Idea: Dynamic planning DP

Recursion formula DP [i] = max (DP [i-1], A [i]);

 // input [-2,1,3, -1, -6] 
 // output: [1,3] 4 
function maxSum (arr = []) { 
    let tempSum = 0 ; 
    let maxSum = 0 ;
    for (let i = 0; i <arr.length; i ++ ) { 
        tempSum + = arr [i];
        if (tempSum> maxSum) { 
            maxSum = tempSum; 
        } else  if (tempSum <0 ) { 
            tempSum = 0 ; 
        } 
    } 
    return maxSum; 
}}

You can use JS Math method to simplify the code

function maxSum3 (arr = []) { 
    let tempSum = 0 ; 
    let maxSum = 0 ;
    for (let i = 0; i <arr.length; i ++ ) { 
        tempSum = Math.max (tempSum + arr [i], arr [i]); 
        maxSum = Math.max (tempSum, maxSum) 
    } 
    return maxSum; 
}}

 

Or print to define a temporary array dp

function maxSum2(arr = []) {
    let dp = [];
    for (let i = 0; i < arr.length; i++) {
        if (dp[i - 1] > 0) {
            dp[i] = dp[i - 1] + arr[i];
        } else {
            dp[i] = arr[i];
        }
    }
    return Math.max(...dp)
}

 

Guess you like

Origin www.cnblogs.com/ajaxkong/p/12731491.html