diff --git a/rs/furthest-building-you-can-reach.rs b/rs/furthest-building-you-can-reach.rs index 08fe7f3..31450ff 100644 --- a/rs/furthest-building-you-can-reach.rs +++ b/rs/furthest-building-you-can-reach.rs @@ -3,37 +3,38 @@ use std::collections::BinaryHeap; struct Solution {} impl Solution { - pub fn furthest_building(heights: Vec, bricks: i32, ladders: i32) -> i32 { - let mut furthest = 0; + pub fn furthest_building(heights: Vec, mut bricks: i32, mut ladders: i32) -> i32 { + let mut used: BinaryHeap = 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 } }