Skip to content

Instantly share code, notes, and snippets.

@optimistiks
Created May 18, 2023 13:42
Show Gist options
  • Select an option

  • Save optimistiks/ab37350c4134fd4fbfd4722fdf6b07fa to your computer and use it in GitHub Desktop.

Select an option

Save optimistiks/ab37350c4134fd4fbfd4722fdf6b07fa to your computer and use it in GitHub Desktop.
You’ve been provided with the nums integer array, representing the series of squares. The player starts at the first index and, following the rules of the game, tries to reach the last index. If the player can reach the last index, your function returns TRUE; otherwise, it returns FALSE.
export function jumpGame(nums) {
// take last element as our target
let target = nums.length - 1;
// start iterating from the element preceding the last, backwards
for (let i = nums.length - 2; i >= 0; --i) {
const preceding = i;
const diff = target - preceding;
// the target element is reachable from the preceding element,
// if preceding element value is greater or equal to the difference between target and preceding index
// for example, element at index 5 is reachable from element at index 4 if value at index 4 is 1 or more
// element at index 4 is reachable from element at index 1 if value at index 1 is 3 or more
if (nums[preceding] >= diff) {
// if target is reachable, make preceding element our new target
target = preceding;
}
}
// if we reached element at index 0, it means we have a path, otherwise we don't have a path
return target === 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment