Implement the jumpGameReachableGreedy method that checks whether the last index is reachable using greedy logic.
The input array nums represents jump power at each index. From index i, you may jump at most nums[i] positions forward.
Your task is to check whether it is possible to reach the last index starting from index 0.
For example, [2,3,1,1,4] returns true because the last index can be reached, but [3,2,1,0,4] returns false because the jump path gets stuck at index 3.
Example 1
Input
nums (int[]) =
[2,3,1,1,4]size (int) =
5Returns (boolean)
trueExample 2
Input
nums (int[]) =
[3,2,1,0,4]size (int) =
5Returns (boolean)
falseExample 3
Input
nums (int[]) =
[0]size (int) =
1Returns (boolean)
trueTrack the farthest index that can be reached so far.
Scan the array from left to right. If the current index is greater than the farthest reachable index, you cannot stand on this position, so return false. Otherwise, update the farthest reachable index using i + nums[i].
If the farthest reachable index reaches or passes the last index, return true.
Pseudocode:
function jumpGameReachableGreedy(nums, size):
farthest = 0
for i from 0 to size - 1:
if i > farthest:
return false
farthest = max(farthest, i + nums[i])
if farthest >= size - 1:
return true
return trueReady to test your solutionRun Code checks your solution against the test cases.Shift + Enter to run