Search code examples
javascriptkadanes-algorithm

Maximum Subarray using javascript


Given an integer array nums,

find the contiguous subarray (containing at least one number)

which has the largest sum and return its sum.

Example:

Input: [-2,1,-3,4,-1,2,1,-5,4],

Output: 6

Explanation: [4,-1,2,1] has the largest sum = 6.

Inputs:[-1]

Output:-1

Inputs:[-2,-1]

Outputs:[-1]

What i try in my JS:

 
    var maxSubArray = function(nums) {
    result=0
    negativenumber=[]
    for(i=0;i<nums.length;i++){
        if(nums[i]<0){
            negativenumber.push(nums[i]);
    }else{
      result+=nums[i];
    }
    }
    return result;
};
maxSubArray([-2,1,-3,4,-1,2,1,-5,4])//should return 6
maxSubArray([-1])//should return -1
maxSubArray([-1,-2])//should return -1


Solution

  • You can use Kadane's algorithm.

    function maxSum(arr){
      let a1 = 0
      let a2 = arr[0]
      arr.forEach((i) => {
        a1 = Math.max(i, a1 + i)
        a2 = Math.max(a2, a1)
      })
      return a2
    }
    console.log(maxSum([-2,1,-3,4,-1,2,1,-5,4]))
    console.log(maxSum([-1]))
    console.log(maxSum([-1,-2]))