Last active
April 23, 2019 11:14
-
-
Save MithraTalluri/8e87d45558666825db607f2bd6cfe579 to your computer and use it in GitHub Desktop.
Maximum Subarray Sum with indices on 1D array (Kadane's Algorithm)
This file contains hidden or 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
| 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