1
0
Fork 0
mirror of https://gitlab.com/mfocko/LeetCode.git synced 2024-11-09 15:59:06 +01:00

rs: fix «1642. Furthest Building You Can Reach»

Signed-off-by: Matej Focko <mfocko@redhat.com>
This commit is contained in:
Matej Focko 2024-02-17 23:30:20 +01:00
parent 3521bf1f37
commit 145bbe66e8
Signed by: mfocko
GPG key ID: 7C47D46246790496

View file

@ -3,37 +3,38 @@ use std::collections::BinaryHeap;
struct Solution {}
impl Solution {
pub fn furthest_building(heights: Vec<i32>, bricks: i32, ladders: i32) -> i32 {
let mut furthest = 0;
pub fn furthest_building(heights: Vec<i32>, mut bricks: i32, mut ladders: i32) -> i32 {
let mut used: BinaryHeap<i32> = BinaryHeap::new();
let mut heap: BinaryHeap<(usize, i32, i32)> = BinaryHeap::from([(0, bricks, ladders)]);
while let Some((idx, b, l)) = heap.pop() {
// reached the end or beyond
if idx + 1 >= heights.len() {
furthest = heights.len() - 1;
break;
}
let mut idx = 0;
while idx + 1 < heights.len() {
let h_diff = heights[idx + 1] - heights[idx];
// can hop without resources
if heights[idx] >= heights[idx + 1] {
heap.push((idx + 1, b, l));
// no reason to use ladder or bricks
if h_diff <= 0 {
idx += 1;
continue;
}
// can use bricks
if b >= heights[idx + 1] - heights[idx] {
heap.push((idx + 1, b - heights[idx + 1] + heights[idx], l));
// by default use the bricks
bricks -= h_diff;
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 l > 0 {
heap.push((idx + 1, b, l - 1));
if ladders < 0 {
break;
}
furthest = cmp::max(furthest, idx);
idx += 1;
}
furthest as i32
idx as i32
}
}