45. Jump Game II

Explanation:

To solve this problem, we can use a greedy approach with dynamic programming. We iterate through the array and for each position, we calculate the farthest reachable position from that position. We keep track of the current farthest position and the next farthest position we can reach in the current jump. When the current position reaches the current farthest position, we increment the jump count and update the current farthest position with the next farthest position.

Time complexity: O(n)
Space complexity: O(1)

class Solution {
    public int jump(int[] nums) {
        int n = nums.length;
        int jumps = 0;
        int currentFarthest = 0;
        int nextFarthest = 0;

        for (int i = 0; i < n - 1; i++) {
            nextFarthest = Math.max(nextFarthest, i + nums[i]);
            if (i == currentFarthest) {
                jumps++;
                currentFarthest = nextFarthest;
            }
        }
        
        return jumps;
    }
}

Code Editor (Testing phase)

Improve Your Solution

Use the editor below to refine the provided solution. Select a programming language and try the following:

  • Add import statement if required.
  • Optimize the code for better time or space complexity.
  • Add test cases to validate edge cases and common scenarios.
  • Handle error conditions or invalid inputs gracefully.
  • Experiment with alternative approaches to deepen your understanding.

Click "Run Code" to execute your solution and view the output. If errors occur, check the line numbers and debug accordingly. Resize the editor by dragging its bottom edge.