image.png

+ane’s algorithm

its sort of a greedy algorithm as we are ignoring and counting from different index then goal with some setting

kadane’s algorithm goes like

if we have to find greatest sum possible of a subarray(contiguous)

then we can make a choice like

[4,3,-2,5,3,2,1,-10,12]

then if we start moving from left to right we can go till 4+3 which will give us 7 and then if we add -2 we will get less sum , so we can stop here and start again from ahead of -2,

which will be 5+3+2+1 = 11 then we keep replacing the sum until we hit a value which will give us less value again

let nums =[4,-1,2,-7,3,4]

function calculateGreatestSubarraySum(nums){
         let currSum = 0;
         let greatestSum = nums[0];

         for(let i=1; i<nums.length ;i++){
            currSum = Math.max(currSum,0);
            currSum += nums[i];
            greatestSum = Math.max(currSum,greatestSum)
         }
         

         return greatestSum
}

console.log(calculateGreatestSubarraySum(nums))