# Jump Game II in Python

PythonServer Side ProgrammingProgramming

#### Beyond Basic Programming - Intermediate Python

Most Popular

36 Lectures 3 hours

#### Practical Machine Learning using Python

Best Seller

91 Lectures 23.5 hours

#### Practical Data Science using Python

22 Lectures 6 hours

Suppose we have one array of integers, where all elements are positive. The initial starting point is at index 1. Each element in the array represents our maximum jump length at that position. Our goal is to reach to the final cell with less number of jumps. So if the array is like [2,3,1,1,4], and then the output will be 2, as we can jump to index 1 from 0, then jump to index 4, that is the last index.

To solve this, we will follow these steps −

• end := 0, jumps := 0, farthest := 0

• for i in range 0 to length of nums – 1

• farthest := max of farthest and nums[i] + i

• if i is end, and i is not length of nums – 1, then

• increase jumps by 1

• end := farthest

• return jumps

## Example

Let us see the following implementation to get a better understanding −

Live Demo

class Solution(object):
def jump(self, nums):
end = 0
jumps = 0
farthest = 0
for i in range(len(nums)):
farthest = max(farthest,nums[i]+i)
if i == end and i != len(nums)-1:
jumps+=1
end = farthest
return jumps
ob = Solution()
print(ob.jump([2,3,1,1,4]))

## Input

[2,3,1,1,4]

## Output

2