1642. Furthest Building You Can Reach
Asked at 12Amazon42Google23Bloomberg14Meta8.5DE Shaw62oyo88Media.net79Twilio64PhonePe64Walmart Labs43Uber30TikTok26
Problem
Walk from building 0 to the right. Stepping down or level is free; stepping up by d costs either one ladder or d bricks. Using your bricks and ladders optimally, return the furthest building index you can reach.
Example: heights = [4,2,7,6,9,14,12], bricks = 5, ladders = 1 → 4
Constraints: n ≤ 10⁵.
Use ladders for the largest climbs. Push every climb into a min-heap; when the heap exceeds ladders, the smallest climb gets paid with bricks instead. Stop when bricks go negative.
Complexity: O(n log ladders).
class Solution:
def furthestBuilding(self, heights: List[int], bricks: int, ladders: int) -> int:
h = []
for i in range(len(heights) - 1):
d = heights[i + 1] - heights[i]
if d <= 0:
continue
heappush(h, d)
if len(h) > ladders:
bricks -= heappop(h)
if bricks < 0:
return i
return len(heights) - 1
assert Solution().furthestBuilding([4, 2, 7, 6, 9, 14, 12], 5, 1) == 4
assert Solution().furthestBuilding([4, 12, 2, 7, 3, 18, 20, 3, 19], 10, 2) == 7
assert Solution().furthestBuilding([14, 3, 19, 3], 17, 0) == 3
class Solution {
public int furthestBuilding(int[] heights, int bricks, int ladders) {
PriorityQueue<Integer> pq = new PriorityQueue<>();
for (int i = 0; i < heights.length - 1; i++) {
int d = heights[i + 1] - heights[i];
if (d <= 0) continue;
pq.add(d);
if (pq.size() > ladders && (bricks -= pq.poll()) < 0) return i;
}
return heights.length - 1;
}
}
type IntHeap []int // min-heap
func (h IntHeap) Len() int { return len(h) }
func (h IntHeap) Less(i, j int) bool { return h[i] < h[j] }
func (h IntHeap) Swap(i, j int) { h[i], h[j] = h[j], h[i] }
func (h *IntHeap) Push(x any) { *h = append(*h, x.(int)) }
func (h *IntHeap) Pop() any {
old := *h
x := old[len(old)-1]
*h = old[:len(old)-1]
return x
}
func furthestBuilding(heights []int, bricks int, ladders int) int {
h := &IntHeap{} // climbs covered by ladders: the largest ones
for i := 0; i+1 < len(heights); i++ {
d := heights[i+1] - heights[i]
if d <= 0 {
continue
}
heap.Push(h, d)
if h.Len() > ladders { // the smallest climb pays with bricks
bricks -= heap.Pop(h).(int)
if bricks < 0 {
return i
}
}
}
return len(heights) - 1
}