We use cookies to ensure you have the best browsing experience on our website. Please read our cookie policy for more information about how we use cookies.
The problem is that you greedily always go forward as much as possible if you can and this is incorrect. Just because you can leap doesn't mean you should. Lets take the following scenario:
leap = 4 and 0 0 0 1 0 1 0 1 1 1 0
You would leap from the 0th index to the 4th (the first zero in between 1's). You would then be stuck and you would falsely return that this game cannot be won. However, you should walk to i = 2, then leap to the second 0 (in between 1s), then finally leap to the end of the board.
This is why the recursive solutions work, if leaping fails, then they try to go back, if that fails, they try to go forward (or in whatever order they put them in). If all three fail, you can't win.
To fix your code, you need to do two things: 1) you need to have a way to try and go forward (and leap from there) and 2) you need to have a way to try and go backwards (and leap from there).
Cookie support is required to access HackerRank
Seems like cookies are disabled on this browser, please enable them to open this website
Join us
Create a HackerRank account
Be part of a 26 million-strong community of developers
Please signup or login in order to view this challenge
Java 1D Array (Part 2)
You are viewing a single comment's thread. Return to all comments →
The problem is that you greedily always go forward as much as possible if you can and this is incorrect. Just because you can leap doesn't mean you should. Lets take the following scenario:
leap = 4 and 0 0 0 1 0 1 0 1 1 1 0
You would leap from the 0th index to the 4th (the first zero in between 1's). You would then be stuck and you would falsely return that this game cannot be won. However, you should walk to i = 2, then leap to the second 0 (in between 1s), then finally leap to the end of the board.
This is why the recursive solutions work, if leaping fails, then they try to go back, if that fails, they try to go forward (or in whatever order they put them in). If all three fail, you can't win.
To fix your code, you need to do two things: 1) you need to have a way to try and go forward (and leap from there) and 2) you need to have a way to try and go backwards (and leap from there).