-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathjump_game_I.py
18 lines (16 loc) · 1.12 KB
/
jump_game_I.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
# Intuition
# Imagine you have a car, and you have some distance to travel (the length of the array). This car has some amount of gasoline, and as long as it has gasoline, it can keep traveling on this road (the array). Every time we move up one element in the array, we subtract one unit of gasoline. However, every time we find an amount of gasoline that is greater than our current amount, we "gas up" our car by replacing our current amount of gasoline with this new amount. We keep repeating this process until we either run out of gasoline (and return false), or we reach the end with just enough gasoline (or more to spare), in which case we return true.
# Note: We can let our gas tank get to zero as long as we are able to gas up at that immediate location (element in the array) that our car is currently at.
# Complexity
# Time complexity: O(n)
# Space complexity: O(1)
class Solution:
def canJump(self, nums: List[int]) -> bool:
gas = 0
for n in nums:
if gas < 0:
return False
elif n > gas:
gas = n
gas -= 1
return True