Skip to content

Instantly share code, notes, and snippets.

@anil477
Created April 10, 2017 09:35
Show Gist options
  • Save anil477/60c79fda40fb63d2ebc73eaed0d36e76 to your computer and use it in GitHub Desktop.
Save anil477/60c79fda40fb63d2ebc73eaed0d36e76 to your computer and use it in GitHub Desktop.
Largest Sum Contiguous Subarray - Kadane Algorithm
import java.io.*;
import java.util.*;
import java.lang.Math;
class Kadane
{
public static void main (String[] args)
{
int [] a = {-2, -3, 4, -1, -2, 1, 5, -3};
//int [] a = {-2, 3, 2, -1};
System.out.println("Maximum contiguous sum is " +
maxSubArraySum(a));
}
static int maxSubArraySum(int a[])
{
int size = a.length;
int max_global = a[0];
int max_current = a[0];
for (int i = 1; i < size-1; i++)
{
max_current = Math.max(a[i], max_current + a[i]);
if( max_current > max_global ){
max_global = max_current;
}
}
return max_global;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment