Skip to content

Commit 01b0e5a

Browse files
author
Joseph Luce
authored
Create 055_jump_game.md
1 parent 17a89c7 commit 01b0e5a

File tree

1 file changed

+31
-0
lines changed

1 file changed

+31
-0
lines changed

leetcode/medium/055_jump_game.md

Lines changed: 31 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,31 @@
1+
# 55. Jump Game
2+
3+
## Best Solution
4+
- Runtime: O(N)
5+
- Space: O(1)
6+
- N = Number of elements in array
7+
8+
You can think of this solution by imagining a car driving down the road, each element in the array represents a gas station.
9+
However, each gas station only allows a refill up to a certain max number.
10+
So if you have 4 gallons of gas in your car and the gas station allows up to 2, you can't refill here.
11+
On the other hand, if you have 2 gallons of gas and the gas station allows up to 3, you take the refill, now your car is set to 3 gallons of gas.
12+
Then its simply driving as far as possible until you run out of gas.
13+
14+
This is a much simplier approach to this question that is not recommended in the solutions of leetcode.
15+
Instead of reversing or backtracking, we just move left to right.
16+
This is still a greedy approach.
17+
18+
```
19+
class Solution:
20+
def canJump(self, nums: List[int]) -> bool:
21+
if len(nums) == 0:
22+
return False
23+
n_jumps, curr_index = 1, 0
24+
while n_jumps != 0:
25+
if curr_index == len(nums)-1:
26+
return True
27+
n_jumps -= 1
28+
n_jumps = max(nums[curr_index], n_jumps)
29+
curr_index += 1
30+
return False
31+
```

0 commit comments

Comments
 (0)