 
  Data Structure Data Structure
 Networking Networking
 RDBMS RDBMS
 Operating System Operating System
 Java Java
 MS Excel MS Excel
 iOS iOS
 HTML HTML
 CSS CSS
 Android Android
 Python Python
 C Programming C Programming
 C++ C++
 C# C#
 MongoDB MongoDB
 MySQL MySQL
 Javascript Javascript
 PHP PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Jump Game in Python
Suppose we have an array of non-negative integers; we are initially positioned at the first index of the array. Each element in the given array represents out maximum jump length at that position. We have to determine if we are able to reach the last index or not. So if the array is like [2,3,1,1,4], then the output will be true. This is like jump one step from position 0 to 1, then three step from position 1 to the end.
Let us see the steps −
- n := length of array A – 1
- for i := n – 1, down to -1- if A[i] + i > n, then n := i
 
- return true when n = 0, otherwise false
Let us see the following implementation to get better understanding −
Example
class Solution(object): def canJump(self, nums): n = len(nums)-1 for i in range(n-1,-1,-1): if nums[i] + i>=n: n = i return n ==0 ob1 = Solution() print(ob1.canJump([2,3,1,1,4]))
Input
[2,3,1,1,4]
Output
True
Advertisements
 