what is kadane's algorithm code example
Example 1: kadane's algorithm
def kadane(inputArray):
maxSum = float("-inf")
curSum = 0
for x in inputArray:
curSum = max(0, curSum + x)
maxSum = max(maxSum, curSum)
return maxSum
Example 2: kadane algorithm
public int kadane(int[] arr){
int max_so_far = 0, curr_max = Integer.MIN_VALUE;
for(int i: arr){
max_so_far += i;
if(max_so_far<0) max_so_far = 0;
if(max_so_far>curr_max) curr_max = max_so_far;
}
return curr_max;
}
Example 3: kadane algorithm with negative numbers included as sum
int ms,cs;
ms=cs=a[0];
for(int i=1;i<n;i++)
{
cs=max(a[i],cs+a[i]);
ms=max(cs,ms);
}
return ms;