Created
April 10, 2017 09:35
-
-
Save anil477/60c79fda40fb63d2ebc73eaed0d36e76 to your computer and use it in GitHub Desktop.
Largest Sum Contiguous Subarray - Kadane Algorithm
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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