Skip to content

Instantly share code, notes, and snippets.

@anil477
Last active June 28, 2019 17:15
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save anil477/967eb09a4f9d7c89baf01ef00ca5b532 to your computer and use it in GitHub Desktop.
Save anil477/967eb09a4f9d7c89baf01ef00ca5b532 to your computer and use it in GitHub Desktop.
Kadane Algorithm
import java.io.*;
import java.lang.*;
class Test
{
/*
public static void main (String[] args) throws java.lang.Exception
{
int[] a = new int[]{-2, -3, 4, -1, -2, 1, 5, -3};
int l = a.length;
int max_current = a[0];
int max_global = a[0];
for(int i = 1; i < l; i++ )
{
max_current = Math.max(a[i], (max_current + a[i]));
if (max_current > max_global){
max_global = max_current;
}
}
System.out.println(max_global);
}
*/
public static void main (String[] args) throws java.lang.Exception
{
int[] a = new int[]{4, 1, 1, -1, -3, -5, -6, 2, 6, -2};
int l = a.length;
int max_current = a[0];
int max_global = a[0];
int start = 0;
int s = 0;
int e = 0;
for(int i = 1; i < l; i++)
{
if (a[i] > (max_current + a[i])) {
max_current = a[i];
s = i;
} else {
max_current = max_current + a[i];
}
if (max_current > max_global) {
start = s;
e = i;
max_global = max_current;
}
}
System.out.println("max sum: " + max_global);
System.out.println("start index: " + start);
System.out.println("end index: " + e);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment