DEV Community

loading...

Discussion on: Kadane's Algorithm & The Maximum Subarray Problem

Collapse
salyadav profile image
Saloni Yadav

I had a slight modification in this logic.
We can do without maxCurrent, coz if we encounter a -ve number it will always reduce the maxCurrent and a positive number will always increase it...
So we just keep modifying the current array with sum of all past elements as long as they are +ve... and not if -ve.
then we keep comparing maxGlobal with this sum.

var maxSubArray = function(nums) {
    if (nums.length == 0) 
        return 0;
    let max = nums[0];
    for (let i=1; i<nums.length; i++) {
        if (nums[i-1] > 0){
            nums[i] += nums[i-1];
        } 
        max = Math.max(nums[i], max);
    }
    return max;
};