
Sponsored
Sponsored
The greedy approach involves making a jump only when absolutely necessary. Track the maximum index you can reach at each step and make a decision to jump when you get to the maximum of the current window. This ensures the least number of jumps.
Time Complexity: O(n), where n is the number of elements in the array, because we make a single pass through the array.
Space Complexity: O(1), since we are using a fixed amount of extra space.
1class Solution:
2 def jump(self, nums):
3 jumps = 0
4 current_end = 0
5 farthest = 0
6 for i in range(len(nums) - 1):
7 farthest = max(farthest, i + nums[i])
8 if i == current_end:
9 jumps += 1
10 current_end = farthest
11 return jumps
12
13# Test
14sol = Solution()
15nums = [2, 3, 1, 1, 4]
16print("Minimum jumps:", sol.jump(nums))Through a single pass from the start to the end of the array, determine the `farthest` point reachable and adjust the jump point at `currentEnd`.
The dynamic programming approach calculates the minimum jumps required to reach each index. For each index, calculate the minimum number of jumps required from all previous indices that can reach the current index. However, this approach is less efficient in terms of time complexity.
Time Complexity: O(n^2), where n is the number of elements.
Space Complexity: O(n), due to the use of a DP array.
1function
Use a dynamic programming approach with an array initialized to `Infinity`. Update each index with the smallest known number of jumps from previous indices that can reach it.