LeetCode 45: Jump Game II
Problem Description
Explanation:
To solve this problem, we can use a greedy approach with dynamic programming. We iterate through the array and for each position, we calculate the farthest reachable position from that position. We keep track of the current farthest position and the next farthest position we can reach in the current jump. When the current position reaches the current farthest position, we increment the jump count and update the current farthest position with the next farthest position.
Time complexity: O(n)
Space complexity: O(1)
Solutions
class Solution {
public int jump(int[] nums) {
int n = nums.length;
int jumps = 0;
int currentFarthest = 0;
int nextFarthest = 0;
for (int i = 0; i < n - 1; i++) {
nextFarthest = Math.max(nextFarthest, i + nums[i]);
if (i == currentFarthest) {
jumps++;
currentFarthest = nextFarthest;
}
}
return jumps;
}
}
Related LeetCode Problems
Loading editor...