Created
December 31, 2016 09:16
-
-
Save Muzietto/bc0663f4612c99f3394f80762207effb to your computer and use it in GitHub Desktop.
Human-readable solution for the problem at the end of https://codility.com/media/train/12-BinarySearch.pdf
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
function boardsBinarySearch(A, numBoards) { | |
var n = A.length; | |
var minBoardSize = 1; | |
var maxBoardSize = n; | |
var result = -1; | |
while (minBoardSize <= maxBoardSize) { | |
var tentativeBoardSize = Math.floor((minBoardSize + maxBoardSize) / 2); | |
if (neededBoards(A, tentativeBoardSize) <= numBoards) { | |
result = tentativeBoardSize; | |
maxBoardSize = tentativeBoardSize - 1; | |
} else { | |
minBoardSize = tentativeBoardSize + 1; | |
} | |
} | |
return result; | |
} | |
function neededBoards(A, boardSize) { | |
var beginLastBoard = -1; | |
var numBoards = 0; | |
for (var i = 0; i < A.length; i++) { | |
if (!A[i]) continue; // solid wood | |
if (beginLastBoard > 0 && (beginLastBoard + boardSize -1) >= i) continue; // there's a board, and it's still covering the hole | |
numBoards++; | |
beginLastBoard = i; | |
} | |
return numBoards; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment