Could someone take me through what is happening here in Kadane's algorithm? Wanted to check my understanding. here's how I see it.
you are looping through the array, and each time you set the ans variable to the largest value seen, until that value becomes negative, then ans becomes zero.
At the same time, the sum variable is overwritten each time through the loop, to the max between previously seen sums or the largest 'ans' so far. Once the loop is finished executing you will have the largest sum or answer seen so far!
var sumArray = function(array) {
var ans = 0;
var sum = 0;
//loop through the array.
for (var i = 0; i < array.length; i++) {
//this is to make sure that the sum is not negative.
ans = Math.max(0, ans + array[i]);
//set the sum to be overwritten if something greater appears.
sum = Math.max(sum, ans)
}
return sum;
};