Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save antonlogvinenko/584e2c09393a5da9fedc3ac6331bd930 to your computer and use it in GitHub Desktop.
Save antonlogvinenko/584e2c09393a5da9fedc3ac6331bd930 to your computer and use it in GitHub Desktop.
/**
* 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