DEV Community

Debesh P.
Debesh P.

Posted on

45. Jump Game II | LeetCode | Top Interview 150 | Coding Questions

Problem Link

https://leetcode.com/problems/jump-game-ii/


leetcode 45


Solution

class Solution {
    public int jump(int[] nums) {
        int n = nums.length;
        int totalJumps = 0;
        int destination = n - 1;
        int coverage = 0;
        int lastIdx = 0;

        // base case
        if(n == 1) return 0;

        for(int i=0; i<n; i++) {
            coverage = Math.max(coverage, i+nums[i]);
            if(i == lastIdx) {
                lastIdx = coverage;
                totalJumps++;
                if(coverage >= destination) {
                    return totalJumps;
                }
            }
        }

        return totalJumps;
    }
}
Enter fullscreen mode Exit fullscreen mode

Top comments (0)