LeetCode Medium Challenge Day 13 | Jump Game
QUESTION LINK - CLICK
Problem Statement:
You are given an array nums where nums[i] represents the maximum number of steps you can jump forward from that position. You need to determine if you can reach the last index starting from the first index.
Step-by-Step Explanation:
1. Initialization:
- goal is initialized to the last index of the array (`nums.length - 1`). This variable represents the position we want to reach.
2. Iterating Backwards through the Array:
- A for loop iterates from the last index to the first index (right to left).
- For each index i, the condition i + nums[i] >= goal is checked:
- This condition checks if you can jump from the current index i to or beyond the current goal.
领英推荐
3. Updating the Goal:
- If the condition i + nums[i] >= goal is true, it means you can jump from index i to or beyond the current goal. In this case, update goal to the current index i.
4. Checking the Result:
- After the loop completes, check if goal is 0. If goal is 0, it means you can reach the last index from the first index, and the function returns true.
- If goal is not 0, it means you cannot reach the last index, and the function returns false.
CODE
class Solution {
public boolean canJump(int[] nums) {
int goal = nums.length - 1;
for (int i = goal; i >= 0; i--) {
if (i + nums[i] >= goal) {
goal = i;
}
}
return goal == 0;
}
}