Thinking process - dp
O(n^2)
dp[i] = the minimum number of jumps needed to reach position i
Thinking process - bfs
O(n)
add reachable elements to a queue
Mistakes
- don't use queue, otherwise it's O(n^2) as well
- currIndex is changing, so currMax should be equal to maxIndex
public class Solution {
public int jump(int[] nums) {
if (nums.length <= 1) return 0;
int result = 0;
int currIndex = 0;
int maxIndex = 0;
int currMax = 0;
while (currIndex < nums.length) {
result++;
for (; currIndex <= currMax; ++currIndex) {
maxIndex = Math.max(maxIndex, currIndex + nums[currIndex]);
if (maxIndex >= nums.length - 1) {
return result;
}
}
currMax = maxIndex;
}
return 0;
}
}