Solving : Jump Game ||, using Greedy Approch

Today I’m going to solve Jump Game II using a greedy approach.
This solution runs in O(n) time and uses O(1) extra space.

Instead of directly trying to count the jumps at every step, we focus on the maximum coverage (the farthest index we can currently reach). The idea is: in each “window” of indices that we can reach with the current jump, we try to extend our coverage as far as possible, so that the next jump takes us closer to the end.

I struggled with this problem at first. The recursive solution is very slow, and more general methods are also time-consuming. The greedy approach, however, sets everything up in a very efficient and elegant way.

To implement it, I use three main variables:

  • totalJumps – counts how many jumps we have made so far.

  • currentEnd (or destination) – the end of the current coverage window; when we reach this index, we must make a jump.

  • farthest – the farthest index we can reach from any index inside the current window.

As we iterate through the array, for each index i we update farthest = max(farthest, i + nums[i]).
Whenever we reach currentEnd, we increase totalJumps and move currentEnd to farthest. In other words, from all positions in the current window, we choose the jump that gives us maximum coverage, and that defines our next jump boundary.

This way, we greedily expand our coverage window and reach the last index using the minimum number of jumps.




let solve = (nums) =>
{
let jump=0
let cover=0
let ljump=0
let n=nums.length

for(let i=0; i<n-1; i++) {
cover = Math.max(cover, i+nums[i])
if(i == ljump) {
ljump = cover
jump++

if(cover >= n) {
return jump
}
}
}
return jump
}

nums = [2, 4, 1, 2, 3, 1, 1, 2]
console.log(solve(nums))

Comments

Popular posts from this blog

C linking with Masm64

Learning Recursion based Permutations

Learning MergeSort with JS