This page explains Java solution to problem Jump Game II
using Greedy algorithm
.
Given an array of non-negative integers, you are initially positioned at the first index of the array. Each element in the array represents your maximum jump length at that position.
Your goal is to reach the last index in the minimum number of jumps.
Example 1:Input: [2,3,1,1,4]
Output: 2
package com.vc.hard;
class JumpGameIi {
public int jump(int[] nums) {
if(nums == null || nums.length < 2) return 0;
int jumps = 0, farthestWithMinimumJump = 0, farthestAtIndex = 0;
for(int i = 0; i < nums.length - 1; i++) {
farthestAtIndex = Math.max(farthestAtIndex, i + nums[i]);
if(i >= farthestWithMinimumJump) {
farthestWithMinimumJump = farthestAtIndex;
jumps++;
}
}
return jumps;
}
}
O(N)
Where N is total number of elements in an input array
O(1)