From e47ca45b7afca5685d7bd295c360aa891bde1d0e Mon Sep 17 00:00:00 2001 From: Oleksii Trekhleb Date: Mon, 9 Jul 2018 17:59:36 +0300 Subject: [PATCH] Add greedy solution for Jump Game. --- .../uncategorized/jump-game/grdJumpGame.js | 26 +++++++++++++++++++ 1 file changed, 26 insertions(+) create mode 100644 src/algorithms/uncategorized/jump-game/grdJumpGame.js diff --git a/src/algorithms/uncategorized/jump-game/grdJumpGame.js b/src/algorithms/uncategorized/jump-game/grdJumpGame.js new file mode 100644 index 00000000..5cba2e85 --- /dev/null +++ b/src/algorithms/uncategorized/jump-game/grdJumpGame.js @@ -0,0 +1,26 @@ +/** + * GREEDY approach of solving Jump Game. + * + * @param {number[]} numbers - array of possible jump length. + */ +export default function grdJumpGame(numbers) { + // The "good" cell is a cell from which we may jump to the last cell of the numbers array. + + // The last cell in numbers array is for sure the "good" one since it is our goal to reach. + let leftGoodPosition = numbers.length - 1; + + // Go through all numbers from right to left. + for (let numberIndex = numbers.length - 2; numberIndex >= 0; numberIndex -= 1) { + // If we can reach the "good" cell from the current one then for sure the current + // one is also "good". Since after all we'll be able to reach the end of the array + // from it. + const maxCurrentJumpLength = numberIndex + numbers[numberIndex]; + if (maxCurrentJumpLength >= leftGoodPosition) { + leftGoodPosition = numberIndex; + } + } + + // If the most left "good" position is the zero's one then we may say that it IS + // possible jump to the end of the array from the first cell; + return leftGoodPosition === 0; +}