JavaScript solution. With inline explanation.


  • 0
    D
    /**
     * @param {number[]} nums
     * @return {number}
     */
    var maxSubArray = function(nums) {
        
      let maxSum = nums[0];
      let currentSum = nums[0];
      for(let i = 1; i < nums.length; i++){
        
        // sum when current item is considered
        currentSum += nums[i];
        
        // take max of maxSum, currentsum(from above statement), and just the current item
        maxSum = Math.max(...[maxSum, currentSum, nums[i]]);
        
        // if max sum is equal to current item
        // subarray should start from current item
        if(maxSum == nums[i]){
          currentSum = nums[i];
        } else {
            
          // if previous-sum + current-item ( = current sum) is greater than current item
          // consider current item...
          if(currentSum > nums[i]){
            nums[i] = currentSum; // dynamic programming 
          }else {
              
            // else it means previous sum is in negative
            // so in the next round start subarray from current item (void the previous sum)
            currentSum = nums[i];
          }
        }
      }
      
        return maxSum;
        
    };
    
    
    
    

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.