Created
September 4, 2012 18:44
-
-
Save arunma/3624849 to your computer and use it in GitHub Desktop.
Maximum sum Subarray problem - Kadane's algorithm - Java
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
package me.rerun; | |
public class Kadane { | |
public static void main(String[] args) { | |
int[] intArr={3, -1, -1, -1, -1, -1, 2, 0, 0, 0 }; | |
//int[] intArr = {-1, 3, -5, 4, 6, -1, 2, -7, 13, -3}; | |
//int[] intArr={-6,-2,-3,-4,-1,-5,-5}; | |
findMaxSubArray(intArr); | |
} | |
public static void findMaxSubArray(int[] inputArray){ | |
int maxStartIndex=0; | |
int maxEndIndex=0; | |
int maxSum = Integer.MIN_VALUE; | |
int cumulativeSum= 0; | |
int maxStartIndexUntilNow=0; | |
for (int currentIndex = 0; currentIndex < inputArray.length; currentIndex++) { | |
int eachArrayItem = inputArray[currentIndex]; | |
cumulativeSum+=eachArrayItem; | |
if(cumulativeSum>maxSum){ | |
maxSum = cumulativeSum; | |
maxStartIndex=maxStartIndexUntilNow; | |
maxEndIndex = currentIndex; | |
} | |
else if (cumulativeSum<0){ | |
maxStartIndexUntilNow=currentIndex+1; | |
cumulativeSum=0; | |
} | |
} | |
System.out.println("Max sum : "+maxSum); | |
System.out.println("Max start index : "+maxStartIndex); | |
System.out.println("Max end index : "+maxEndIndex); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
This code overworked. Commentators have left the wrong options. They do not consider negative numbers, did not read the problem carefully on Wikipedia. Working easy example:
Supplemented, with indexes:
Fully: