The maximum subsequence and dynamic programming

Given the nums an array of integers, and find a maximum of the successive sub-array (sub-array comprising a minimum element) having its maximum and returns.

Example:

Input: [-2,1, -3,4, -1,2,1, -5,4],
output: 6
Explanation: continuous subarray [4, -1,2,1], and the maximum was 6 .
Advanced:

If you have implemented a complexity of O (n) of the solution, try to solve a more sophisticated use of divide and conquer.

1. Violence

var maxSubArray = function(nums) {
    let start  = 0;
    let end = 0;
    let sum = nums[0];
   for(let i=0;i<nums.length;i++){
        let nowSum = 0;
    for(let j=i;j<nums.length;j++){
         nowSum = nowSum + nums[j];
        if(nowSum >sum){
            sum = nowSum;
            start =i;
            end = j;
        }
    }
   }

   return sum;
 
};

 

2. Dynamic Programming

 

var maxSubArray = function (the nums) { 
the let max = the nums [0 ]; 
    
    the let R & lt = []; // save the maximum data each 
    R & lt [0] = the nums [0 ]; 
    the let SUM = the nums [0 ];
     for (I = the let. 1; I <nums.length; I ++ ) { 
        R & lt [I] = Math.max (R & lt [-I. 1] + the nums [I], the nums [I]); // before the comparison with the current and value whichever is greater, start looking for more data from the largest data. 
        
        IF (<SUM R & lt [I]) { 
            SUM = R & lt [I]; 
        } 
    } 
    return SUM; 
 
};

Realization: there is a problem. Dynamic Programming.

 

 

Source: stay button (LeetCode)
link: https: //leetcode-cn.com/problems/maximum-subarray
copyrighted by deduction from all networks. Commercial reprint please contact the authorized official, non-commercial reprint please indicate the source.

Guess you like

Origin www.cnblogs.com/panjingshuang/p/11687942.html