Skip to content

Instantly share code, notes, and snippets.

@MithraTalluri
Last active April 23, 2019 11:14
Show Gist options
  • Select an option

  • Save MithraTalluri/8e87d45558666825db607f2bd6cfe579 to your computer and use it in GitHub Desktop.

Select an option

Save MithraTalluri/8e87d45558666825db607f2bd6cfe579 to your computer and use it in GitHub Desktop.
Maximum Subarray Sum with indices on 1D array (Kadane's Algorithm)
public static int KadaneWithIndices(int[] array){
int currentMax = 0;
int totalMax = Integer.MIN_VALUE;
int startIndex = 0, endIndex = 0, tempIndex = 0;
for(int i = 0; i < array.length; i++){
currentMax += array[i];
if(currentMax < 0){
currentMax = 0;
tempIndex = i + 1;
}
else if(totalMax < currentMax){
totalMax = currentMax;
startIndex = tempIndex;
endIndex = i;
}
}
System.out.println("Start index: " + startIndex + " End index: " + endIndex);
return totalMax;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment