You are given an integer array nums
. You are initially positioned at the array’s first index, and each element in the array represents your maximum jump length at that position.
Return true
if you can reach the last index, or false
otherwise.
Example 1:
Input: nums = [2,3,1,1,4]
Output: true
Explanation: Jump 1 step from index 0 to 1, then 3 steps to the last index.
Example 2:
Input: nums = [3,2,1,0,4]
Output: false
Explanation: You will always arrive at index 3 no matter what. Its maximum jump length is 0, which makes it impossible to reach the last index.
1 <= nums.length <= 10^4
0 <= nums[i] <= 10^5
To solve this problem, we can utilize a greedy approach. We need to keep track of the farthest point that can be reached while iterating through the array. Here’s the plan:
maxReach
to keep track of the maximum index we can reach so far.i
:
i
is greater than maxReach
, it means we can’t reach index i
, hence return false
.maxReach
to be the maximum of maxReach
and i + nums[i]
.maxReach
is greater than or equal to the last index of the array, return true
.true
if the loop completes successfully.public class JumpGame {
public boolean canJump(int[] nums) {
int maxReach = 0;
for (int i = 0; i < nums.length; i++) {
if (i > maxReach) {
return false;
}
maxReach = Math.max(maxReach, i + nums[i]);
if (maxReach >= nums.length - 1) {
return true;
}
}
return true;
}
public static void main(String[] args) {
JumpGame jumpGame = new JumpGame();
int[] nums1 = {2, 3, 1, 1, 4};
int[] nums2 = {3, 2, 1, 0, 4};
System.out.println(jumpGame.canJump(nums1)); // Output: true
System.out.println(jumpGame.canJump(nums2)); // Output: false
}
}
n
is the length of the input array. We are iterating through the array once.This solution effectively determines whether you can reach the end of the array using a greedy approach, making it efficient and straightforward.
Got blindsided by a question you didn’t expect?
Spend too much time studying?
Or simply don’t have the time to go over all 3000 questions?