Skip to content

Commit 15e63b3

Browse files
committed
D. J.:
- Added leetcode problem and solution for 45 Jump Game II
1 parent d012e98 commit 15e63b3

File tree

3 files changed

+42
-0
lines changed

3 files changed

+42
-0
lines changed

README.md

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -6,6 +6,7 @@ This repository contains awesome LeetCode problems and solutions written in Pyth
66

77
- [26 Remove Duplicates from Sorted Array](https://leetcode.com/problems/remove-duplicates-from-sorted-array/description/)
88
- [27 Remove Element](https://leetcode.com/problems/remove-element/description/)
9+
- [45 Jump Game II](https://leetcode.com/problems/jump-game-ii/description/)
910
- [55 Jump Game](https://leetcode.com/problems/jump-game/description/)
1011
- [80 Remove Duplicates from Sorted Array II](https://leetcode.com/problems/remove-duplicates-from-sorted-array-ii/description/)
1112
- [88 Merge Sorted Array](https://leetcode.com/problems/merge-sorted-array/description/)
Lines changed: 24 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,24 @@
1+
from typing import List
2+
3+
4+
class Solution:
5+
def jump(self, nums: List[int]) -> int:
6+
"""
7+
You are given a 0-indexed array of integers nums of length n. You are initially positioned at nums[0].
8+
9+
Each element nums[i] represents the maximum length of a forward jump from index i. In other words,
10+
if you are at nums[i], you can jump to any nums[i + j] where:
11+
- 0 <= j <= nums[i] and i + j < n
12+
13+
Return the minimum number of jumps to reach nums[n - 1]. The test cases are generated such that you can reach nums[n - 1].
14+
"""
15+
16+
left, right, jumps = 0, 0, 0
17+
while right < len(nums) - 1:
18+
largest_jump = 0
19+
for i in range(left, right + 1):
20+
largest_jump = max(largest_jump, i + nums[i])
21+
left = right + 1
22+
right = largest_jump
23+
jumps += 1
24+
return jumps

tests/test_45_jump_game_II.py

Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,17 @@
1+
from typing import List
2+
3+
import pytest
4+
5+
from awesome_python_leetcode._45_jump_game_II import Solution
6+
7+
8+
@pytest.mark.parametrize(
9+
argnames=["nums", "expected"],
10+
argvalues=[
11+
([2, 3, 1, 1, 4], 2),
12+
([2, 3, 0, 1, 4], 2),
13+
],
14+
)
15+
def test_func(nums: List[int], expected: int):
16+
num_jumps = Solution().jump(nums)
17+
assert num_jumps == expected

0 commit comments

Comments
 (0)