# kadane's algorithm snippet in c

user8083

``````# Python program to find maximum contiguous subarray

def maxSubArraySum(a,size):

max_so_far =a[0]
curr_max = a[0]

for i in range(1,size):
curr_max = max(a[i], curr_max + a[i])
max_so_far = max(max_so_far,curr_max)

return max_so_far

# Driver function to check the above function
a = [-2, -3, 4, -1, -2, 1, 5, -3]
print"Maximum contiguous sum is" , maxSubArraySum(a,len(a))

#This code is contributed by _Devesh Agrawal_
``````

user1789

``````int maxSubArraySum(int a[], int size)
{
int max_so_far = INT_MIN, max_ending_here = 0;

for (int i = 0; i < size; i++)
{
max_ending_here = max_ending_here + a[i];
if (max_so_far < max_ending_here)
max_so_far = max_ending_here;

if (max_ending_here < 0)
max_ending_here = 0;
}
return max_so_far;
}``````

## maximum subarray sum java

user5199

``````import java.io.*;
// Java program to print largest contiguous array sum
import java.util.*;

{
public static void main (String[] args)
{
int [] a = {-2, -3, 4, -1, -2, 1, 5, -3};
System.out.println("Maximum contiguous sum is " +
maxSubArraySum(a));
}

static int maxSubArraySum(int a[])
{
int size = a.length;
int max_so_far = Integer.MIN_VALUE, max_ending_here = 0;

for (int i = 0; i < size; i++)
{
max_ending_here = max_ending_here + a[i];
if (max_so_far < max_ending_here)
max_so_far = max_ending_here;
if (max_ending_here < 0)
max_ending_here = 0;
}
return max_so_far;
}
}
``````

user1388

``````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;
}``````

user5200

``````static int maxSubArraySum(int a[],int size)
{

int max_so_far = 0, max_ending_here = 0;

for (int i = 0; i < size; i++)
{
max_ending_here = max_ending_here + a[i];
if (max_ending_here < 0)
max_ending_here = 0;

/* Do not compare for all
elements. Compare only
when max_ending_here > 0 */
else if (max_so_far < max_ending_here)
max_so_far = max_ending_here;

}
return max_so_far;
}

// This code is contributed by ANKITRAI1
``````