GV

GeezerVison

The World Wide Web, restored to 800 pixels of glory.

Home|About|Gaming cabinet|Archives|How it works|Starter sites

On this site

  • Sign in
  • ActionsCI/CD and automation
  • CodespacesCloud development environments
  • All Features
  • Documentation
  • Training
  • Certifications
  • Build with Copilot
  • Customize Copilot
  • Integrations
  • Trending repos
  • GitHub Sponsors
  • Developer articles
  • Enterprises

This view

  • Original page
  • New address

GeezerVison is showing github.com — coding-problems/Arrays/jump_game.py at master · XrosLiang/coding-problems

Expand file tree

/

jump_game.py

Copy path
More file actions
More file actions

Latest commit

 

History

History
History
55 lines (41 loc) · 1.21 KB
/

jump_game.py

Copy path

File metadata and controls

55 lines (41 loc) · 1.21 KB
Raw
Copy raw file
Download raw file
Open symbols panel
Edit and raw actions
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
'''
Jump Game
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.
Determine if you are able to reach the last index.
Input: [2, 3, 1, 1, 4]
Output: True
Input: [3, 2, 1, 0, 4]
Output: False
=========================================
Just iterate the array and in each step save the farthest reachable position.
If the current position is smaller than the farthest position, then the end isn't reachable.
Time Complexity: O(N)
Space Complexity: O(1)
'''
############
# Solution #
############
def can_jump(nums):
n = len(nums)
if n == 0:
return False
max_jump = 0
for i in range(n):
# if this field isn't reachable return False
if max_jump < i:
return False
this_jump = i + nums[i]
max_jump = max(max_jump, this_jump)
# if the jump is greater or equal to the last element return True
if max_jump >= n - 1:
return True
###########
# Testing #
###########
# Test 1
# Correct result => True
print(can_jump([2, 3, 1, 1, 4]))
# Test 2
# Correct result => False
print(can_jump([3, 2, 1, 0, 4]))
You are visitor 01402792 — GeezerVison does not store the pages you look up.
Best viewed with Netscape Navigator 4.7 or Internet Explorer 6 at 800×600. No cookies required.