|  | 
| 2 | 2 | 
 | 
| 3 | 3 | // #Medium #Top_100_Liked_Questions #Array #Dynamic_Programming #Greedy | 
| 4 | 4 | // #Algorithm_II_Day_13_Dynamic_Programming #Dynamic_Programming_I_Day_4 | 
| 5 |  | -// #Big_O_Time_O(n)_Space_O(1) #2024_11_10_Time_0_ms_(100.00%)_Space_44.9_MB_(75.73%) | 
|  | 5 | +// #Big_O_Time_O(n)_Space_O(1) #2024_11_10_Time_0_ms_(100.00%)_Space_45_MB_(64.44%) | 
| 6 | 6 | 
 | 
| 7 | 7 | public class Solution { | 
| 8 |  | -    public int jump(int[] nums) { | 
| 9 |  | -        if (nums.length == 1) { | 
| 10 |  | -            return 0; | 
|  | 8 | +    private int getMax(int[] nums, int l, int r) { | 
|  | 9 | +        int max = -1; | 
|  | 10 | +        int curr = -1; | 
|  | 11 | +        for (int i = l; i <= r; i++) { | 
|  | 12 | +            curr = i + nums[i]; | 
|  | 13 | +            max = Math.max(max, curr); | 
| 11 | 14 |         } | 
| 12 |  | -        return minJumps(nums, 0, 0); | 
|  | 15 | +        return max; | 
| 13 | 16 |     } | 
| 14 | 17 | 
 | 
| 15 |  | -    private int minJumps(int[] nums, int currIndex, int jumpStatus) { | 
| 16 |  | -        if (currIndex + nums[currIndex] >= nums.length - 1) { | 
| 17 |  | -            return jumpStatus + 1; | 
| 18 |  | -        } | 
| 19 |  | -        int nextIndex = currIndex + 1; | 
| 20 |  | -        int distanceLeft = (nums.length - 1 - (currIndex + 1)) - nums[currIndex + 1]; | 
| 21 |  | -        for (int i = currIndex + 2; i <= (currIndex + nums[currIndex]); i++) { | 
| 22 |  | -            int tempDistanceLeft = (nums.length - 1 - i) - nums[i]; | 
| 23 |  | -            if (distanceLeft > tempDistanceLeft) { | 
| 24 |  | -                distanceLeft = tempDistanceLeft; | 
| 25 |  | -                nextIndex = i; | 
| 26 |  | -            } | 
|  | 18 | +    public int jump(int[] nums) { | 
|  | 19 | +        int l = 0; | 
|  | 20 | +        int r = 0; | 
|  | 21 | +        int jumps = 0; | 
|  | 22 | +        while (r < nums.length - 1) { | 
|  | 23 | +            int prev = r; | 
|  | 24 | +            r = getMax(nums, l, r); | 
|  | 25 | +            l = prev + 1; | 
|  | 26 | +            jumps++; | 
| 27 | 27 |         } | 
| 28 |  | -        return minJumps(nums, nextIndex, jumpStatus + 1); | 
|  | 28 | +        return jumps; | 
| 29 | 29 |     } | 
| 30 | 30 | } | 
0 commit comments