jump-game-vi

This commit is contained in:
Gleb Koval 2022-07-09 23:34:05 +01:00
parent a94f9af1f5
commit c9bc975b1c
Signed by: cyclane
GPG Key ID: 15E168A8B332382C
1 changed files with 22 additions and 0 deletions

22
jump-game-vi/sol.rs Normal file
View File

@ -0,0 +1,22 @@
use std::collections::BinaryHeap;
impl Solution {
pub fn max_result(nums: Vec<i32>, k: i32) -> i32 {
let mut heap = BinaryHeap::new();
let max_step = k as usize;
heap.push((nums[0], 0));
for p in 1..nums.len() {
let mut max_path = heap.peek().unwrap();
while max_path.1 + max_step < p {
heap.pop();
max_path = heap.peek().unwrap();
}
if p == nums.len() - 1 {
return nums[p] + max_path.0;
} else {
heap.push((nums[p] + max_path.0, p));
}
}
nums[0] // Only possible to reach when nums.len() == 1
}
}