Find the largest contiguous subarray sum of an array

To achieve a time complexity of n, greedy algorithms and dynamic programming can be used.

how are you:

function max(arr){
    let max = arr[0],cur = 0 ; 
     for (let i = 0; i < arr.length; i++ ){
         if (cur < 0 ){ // when cur < 0, then just add a negative number Makes the next number smaller, so it can be discarded directly and re-accumulated from the current i
            cur = arr[i];
        }else{
            cur += arr[i];
        }
        if(cur >= max){
            max = cur;
        }
    }
    return max;
}

Dynamic programming:

 1 function max_2(arr){
 2     let max = [],result = 0;
 3     max[0] = 0;
 4     for(let i = 0; i < arr.length; i++){
 5         if(max[i] < 0){
 6             max[i+1] = arr[i];
 7         }else{
 8             max[i+1] = max[i] + arr[i];
 9         }
10         if(max[i+1] > result){
11             result = max[i+1];
12         }
13     }
14     return result;
15 }

In fact, the idea of ​​dynamic programming in this question is very similar to greed. max[i + 1] stores the value of cur every time it goes to i. In comparison, the space complexity of the greedy algorithm is lower and better.

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=324810704&siteId=291194637