Last active
February 2, 2016 01:17
-
-
Save NathanJang/b0a675156e632e61d95d to your computer and use it in GitHub Desktop.
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
/** Returns the starting index of a longest run of two or more consecutive repeated values | |
* in the array `values`. | |
* @param values an array of integer values representing a series of number cube tosses | |
* Precondition: `values.length > 0` | |
* @return the starting index of a run of maximum size; | |
* `-1` if there is no run | |
*/ | |
public final int getLongestRun(final int[] values) { | |
final int NO_RUN = -1; | |
if (values == null || values.length == 0) { return NO_RUN; } | |
if (values.length == 1) { return 0; } | |
int initialPositionOfLongestRun = NO_RUN, | |
maximumSize = 0, | |
currentSize = 0, | |
currentValue = values[values.length - 1]; | |
for (int currentIndex = values.length - 2; currentIndex >= 0; currentIndex -= 1) { | |
if (values[currentIndex] == currentValue) { | |
currentSize += 1; | |
if (currentSize > maximumSize) { | |
maximumSize = currentSize; | |
initialPositionOfLongestRun = currentIndex; | |
} | |
} else { | |
currentValue = values[currentIndex]; | |
currentSize = 0; | |
} | |
} | |
return initialPositionOfLongestRun; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment