Skip to content

Commit b30292a

Browse files
committed
Sync LeetCode submission Runtime - 184 ms (30.91%), Memory - 15.2 MB (100.00%)
1 parent 1c59640 commit b30292a

File tree

2 files changed

+50
-0
lines changed

2 files changed

+50
-0
lines changed

0045-jump-game-ii/README.md

+35
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,35 @@
1+
<p>You are given a <strong>0-indexed</strong> array of integers <code>nums</code> of length <code>n</code>. You are initially positioned at <code>nums[0]</code>.</p>
2+
3+
<p>Each element <code>nums[i]</code> represents the maximum length of a forward jump from index <code>i</code>. In other words, if you are at <code>nums[i]</code>, you can jump to any <code>nums[i + j]</code> where:</p>
4+
5+
<ul>
6+
<li><code>0 &lt;= j &lt;= nums[i]</code> and</li>
7+
<li><code>i + j &lt; n</code></li>
8+
</ul>
9+
10+
<p>Return <em>the minimum number of jumps to reach </em><code>nums[n - 1]</code>. The test cases are generated such that you can reach <code>nums[n - 1]</code>.</p>
11+
12+
<p>&nbsp;</p>
13+
<p><strong class="example">Example 1:</strong></p>
14+
15+
<pre>
16+
<strong>Input:</strong> nums = [2,3,1,1,4]
17+
<strong>Output:</strong> 2
18+
<strong>Explanation:</strong> The minimum number of jumps to reach the last index is 2. Jump 1 step from index 0 to 1, then 3 steps to the last index.
19+
</pre>
20+
21+
<p><strong class="example">Example 2:</strong></p>
22+
23+
<pre>
24+
<strong>Input:</strong> nums = [2,3,0,1,4]
25+
<strong>Output:</strong> 2
26+
</pre>
27+
28+
<p>&nbsp;</p>
29+
<p><strong>Constraints:</strong></p>
30+
31+
<ul>
32+
<li><code>1 &lt;= nums.length &lt;= 10<sup>4</sup></code></li>
33+
<li><code>0 &lt;= nums[i] &lt;= 1000</code></li>
34+
<li>It&#39;s guaranteed that you can reach <code>nums[n - 1]</code>.</li>
35+
</ul>

0045-jump-game-ii/solution.py

+15
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,15 @@
1+
# Approach - Greedy
2+
3+
class Solution:
4+
def jump(self, nums: List[int]) -> int:
5+
jumps = 0
6+
current_jump_end = 0
7+
farthest = 0
8+
9+
for i in range(len(nums) - 1):
10+
farthest = max(farthest, i + nums[i])
11+
if i == current_jump_end:
12+
jumps += 1
13+
current_jump_end = farthest
14+
15+
return jumps

0 commit comments

Comments
 (0)