rs: fix «1642. Furthest Building You Can Reach»
Signed-off-by: Matej Focko <mfocko@redhat.com>
This commit is contained in:
parent
3521bf1f37
commit
145bbe66e8
1 changed files with 21 additions and 20 deletions
|
@ -3,37 +3,38 @@ use std::collections::BinaryHeap;
|
||||||
|
|
||||||
struct Solution {}
|
struct Solution {}
|
||||||
impl Solution {
|
impl Solution {
|
||||||
pub fn furthest_building(heights: Vec<i32>, bricks: i32, ladders: i32) -> i32 {
|
pub fn furthest_building(heights: Vec<i32>, mut bricks: i32, mut ladders: i32) -> i32 {
|
||||||
let mut furthest = 0;
|
let mut used: BinaryHeap<i32> = BinaryHeap::new();
|
||||||
|
|
||||||
let mut heap: BinaryHeap<(usize, i32, i32)> = BinaryHeap::from([(0, bricks, ladders)]);
|
let mut idx = 0;
|
||||||
while let Some((idx, b, l)) = heap.pop() {
|
while idx + 1 < heights.len() {
|
||||||
// reached the end or beyond
|
let h_diff = heights[idx + 1] - heights[idx];
|
||||||
if idx + 1 >= heights.len() {
|
|
||||||
furthest = heights.len() - 1;
|
|
||||||
break;
|
|
||||||
}
|
|
||||||
|
|
||||||
// can hop without resources
|
// no reason to use ladder or bricks
|
||||||
if heights[idx] >= heights[idx + 1] {
|
if h_diff <= 0 {
|
||||||
heap.push((idx + 1, b, l));
|
idx += 1;
|
||||||
continue;
|
continue;
|
||||||
}
|
}
|
||||||
|
|
||||||
// can use bricks
|
// by default use the bricks
|
||||||
if b >= heights[idx + 1] - heights[idx] {
|
bricks -= h_diff;
|
||||||
heap.push((idx + 1, b - heights[idx + 1] + heights[idx], l));
|
used.push(h_diff);
|
||||||
|
|
||||||
|
// if we run out of bricks, use ladder
|
||||||
|
// for the biggest “skip” that used bricks
|
||||||
|
if bricks < 0 {
|
||||||
|
bricks += used.pop().expect("we used some bricks");
|
||||||
|
ladders -= 1;
|
||||||
}
|
}
|
||||||
|
|
||||||
// can use a ladder
|
if ladders < 0 {
|
||||||
if l > 0 {
|
break;
|
||||||
heap.push((idx + 1, b, l - 1));
|
|
||||||
}
|
}
|
||||||
|
|
||||||
furthest = cmp::max(furthest, idx);
|
idx += 1;
|
||||||
}
|
}
|
||||||
|
|
||||||
furthest as i32
|
idx as i32
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
Loading…
Reference in a new issue