Given an array of non-negative integers, you are initially positioned at the first index of the array.
Each element in the array represents your maximum jump length at that position.
Your goal is to reach the last index in the minimum number of jumps.
Example:
Input: [2,3,1,1,4]
Output: 2
Explanation: The minimum number of jumps to reach the last index is 2.
Jump 1 step from index 0 to 1, then 3 steps to the last index.
Note:You can assume that you can always reach the last index.
Answers
Answer:
Given an array of non-negative integers, you are initially positioned at the first index of the array.
Each element in the array represents your maximum jump length at that position.
Your goal is to reach the last index in the minimum number of jumps.
Example:
Input: [2,3,1,1,4]
Output: 2
Explanation: The minimum number of jumps to reach the last index is 2.
Jump 1 step from index 0 to 1, then 3 steps to the last index.
Note:You can assume that you can always reach the last index.
Explanation:
I don't know.......
First Solution -:
def jump(nums):
n = len(nums)
curr_far = min(nums[0], n - 1)
next_far = 0
step = 0
for i in range(n):
if i <= curr_far:
if next_far < i + nums[i]:
next_far = min(i + nums[i], n - 1)
if i == curr_far and curr_far != 0:
curr_far = next_far
step += 1
return step
nums = #Enter a list.
print(jump(nums))
Here is an example of an input/output:
nums = [2,3,1,1,4]
>>> 2
The minimum number of jumps to reach the last index is 2.
Jump 1 step from index 0 to 1, then 3 steps to the last index.
Second solution -:
def __init__(self, nums):
self.nums = nums
def jump(self, nums):
if not nums or len(nums) == 1:
return 0
curr = 0
count = 0
while(curr < len(nums)):
maxReach = -1
index = 0
for i in range(1, nums[curr] + 1):
if curr + i >= len(nums) - 1:
return count + 1
else:
if nums[curr + i] + i > maxReach:
maxReach = nums[curr + i] + i
index = curr + i
curr = index
count += 1
nums = #Enter a list.
game = Solution(nums)
print(game.jump(nums))