|
| 1 | +""" |
| 2 | +Problem Link: https://leetcode.com/problems/jump-game-ii/ |
| 3 | + |
| 4 | +Given an array of non-negative integers nums, you are initially positioned |
| 5 | +at the first index of the array. |
| 6 | +Each element in the array represents your maximum jump length at that position. |
| 7 | +Your goal is to reach the last index in the minimum number of jumps. |
| 8 | +You can assume that you can always reach the last index. |
| 9 | + |
| 10 | +Example 1: |
| 11 | + |
| 12 | +Input: nums = [2,3,1,1,4] |
| 13 | +Output: 2 |
| 14 | +Explanation: The minimum number of jumps to reach the last index is 2. |
| 15 | +Jump 1 step from index 0 to 1, then 3 steps to the last index. |
| 16 | + |
| 17 | +Example 2: |
| 18 | +Input: nums = [2,3,0,1,4] |
| 19 | +Output: 2 |
| 20 | + |
| 21 | +Constraints: |
| 22 | +1 <= nums.length <= 104 |
| 23 | +0 <= nums[i] <= 1000 |
| 24 | +""" |
| 25 | +class Solution: |
| 26 | + def jump(self, nums: List[int]) -> int: |
| 27 | + jumps, end, farthest = 0, 0, 0 |
| 28 | + |
| 29 | + for index in range(len(nums)-1): |
| 30 | + farthest = max(farthest, index + nums[index]) |
| 31 | + |
| 32 | + if end == index: |
| 33 | + jumps += 1 |
| 34 | + end = farthest |
| 35 | + |
| 36 | + return jumps |
0 commit comments