Created
January 13, 2018 18:33
-
-
Save Helenyin123/adfcb83bfbb6a941dc1738c3127375f2 to your computer and use it in GitHub Desktop.
Houzz Interview
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 int minFactory(int[] array, int range) { | |
| int i = 0; | |
| int count = 0; | |
| int start = 0; | |
| while (i < array.length && i <= range) { | |
| if (array[i] == 1) { | |
| start = i; | |
| } | |
| i++; | |
| } | |
| if (start == 0 && array[0] == 0) return -1; | |
| count++; | |
| while (start + range + 1 < array.length) { | |
| start = farMostFactory(array, start, range); | |
| if (start == -1) return -1; | |
| count++; | |
| } | |
| return count; | |
| } | |
| private int farMostFactory(int[] array, int start, int range) { | |
| int i = start + 1; int pos = start; | |
| // if (start + 1 + range >= array.length) return array.length; // The start 1 can cover to the end | |
| while (i < array.length && i - start <= 2 * range + 1) { | |
| if (array[i] == 1) { | |
| pos = i; | |
| } | |
| i++; | |
| } | |
| if (pos == start) return -1; | |
| return pos; | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment