Created
January 4, 2018 10:21
-
-
Save antonlogvinenko/584e2c09393a5da9fedc3ac6331bd930 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
/** | |
* 1) Window can have only one zero. | |
* | |
* 2) Window's right border is expanded to the right on each step. | |
* | |
* 3) When a new zero is detected the left border | |
* is set to prevZeroIndex+1 to exclude the old zero. | |
* | |
* 3) On every step we check if current window is the largest known window. | |
*/ | |
private static int slidingWindow(int[] a) { | |
int wStart = 0; | |
int wEnd = 0; | |
int globalZeroIndex = 0; | |
int globalLength = 0; | |
int currentZeroIndex = 0; | |
int currentLength = 0; | |
for (int i = 0; i < a.length; i++) { | |
wEnd = i; | |
if (a[i] == 1) { | |
currentLength++; | |
} else { | |
wStart = currentZeroIndex + 1; | |
currentLength = wEnd - wStart + 1; | |
currentZeroIndex = wEnd; | |
} | |
if (currentLength > globalLength) { | |
globalZeroIndex = currentZeroIndex; | |
globalLength = currentLength; | |
} | |
} | |
return globalZeroIndex; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment