Skip to content

Commit 4e6849d

Browse files
committed
feat(greedy): add 45_jump_game_ii.rs
1 parent ca8bd8d commit 4e6849d

File tree

2 files changed

+33
-0
lines changed

2 files changed

+33
-0
lines changed

README.md

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -172,3 +172,4 @@ so that you can use `just tf TEST` command to test.
172172
| Problem | Difficulty | Solution |
173173
| - | - | - |
174174
| 55. Jump Game | Medium | [55_jump_game.rs](./tests/55_jump_game.rs) |
175+
| 45. Jump Game II | Medium | [45_jump_game_ii.rs](./tests/45_jump_game_ii.rs) |

tests/45_jump_game_ii.rs

Lines changed: 32 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,32 @@
1+
// 45. Jump Game II
2+
// https://leetcode.com/problems/jump-game-ii/description/
3+
// Topics: Greedy.
4+
// Difficulty: Medium.
5+
6+
#[test]
7+
fn test_45_jump_game_ii() {}
8+
9+
#[derive(Debug)]
10+
pub struct Solution;
11+
12+
// ---------------------------------
13+
// copy to leetcode starts from here
14+
// ---------------------------------
15+
16+
impl Solution {
17+
pub fn jump(nums: Vec<i32>) -> i32 {
18+
let mut jumps = 0;
19+
let mut current_end = 0;
20+
let mut max_reach = 0;
21+
22+
for (i, &item) in nums.iter().enumerate().take(nums.len() - 1) {
23+
max_reach = max_reach.max(i + item as usize);
24+
if i == current_end {
25+
jumps += 1;
26+
current_end = max_reach;
27+
}
28+
}
29+
30+
jumps
31+
}
32+
}

0 commit comments

Comments
 (0)