From c9bc975b1c6c7a221eed66f28c23d0d022e3d8b4 Mon Sep 17 00:00:00 2001 From: Gleb Koval Date: Sat, 9 Jul 2022 23:34:05 +0100 Subject: [PATCH] jump-game-vi --- jump-game-vi/sol.rs | 22 ++++++++++++++++++++++ 1 file changed, 22 insertions(+) create mode 100644 jump-game-vi/sol.rs diff --git a/jump-game-vi/sol.rs b/jump-game-vi/sol.rs new file mode 100644 index 0000000..2ca1f18 --- /dev/null +++ b/jump-game-vi/sol.rs @@ -0,0 +1,22 @@ +use std::collections::BinaryHeap; + +impl Solution { + pub fn max_result(nums: Vec, 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 + } +} \ No newline at end of file