DEV Community

loading...

Discussion on: Solution: Jump Game II

Collapse
rohithv07 profile image
Rohith V

My Java Solution

class Solution {
    public int jump(int[] nums) {
        int length = nums.length;
        if (length == 1)
            return 0;
        int jumps = 0;
        int [] interval = new int [] {0, 0};
        while (true) {
            jumps += 1;
            int canReach = -1;
            for (int i=interval[0]; i<=interval[1]; i++) {
                canReach = Math.max(canReach, i + nums[i]);
            }
            if (canReach >= length - 1) {
                return jumps;
            }
            interval[0] = interval[1] + 1;
            interval[1] = canReach;
        }
    }
}
Enter fullscreen mode Exit fullscreen mode