Furthest Building You Can Reach

medium array greedy heap

Problem

You have an array of building heights, plus bricks and ladders. Moving forward you can step down freely, but stepping up by d uses either d bricks or one ladder. Return the furthest index reachable.

Inputheights = [4,2,7,6,9,14,12], bricks = 5, ladders = 1
Output4
Use bricks for jumps of 2 and 3; save ladder for the jump of 5.

import heapq

def furthest_building(h, bricks, ladders):
    heap = []
    for i in range(len(h) - 1):
        d = h[i + 1] - h[i]
        if d > 0:
            heapq.heappush(heap, d)
            if len(heap) > ladders:
                bricks -= heapq.heappop(heap)
                if bricks < 0: return i
    return len(h) - 1
function furthestBuilding(h, bricks, ladders) {
  const heap = []; // min-heap of jump sizes
  const push = x => { heap.push(x); heap.sort((a, b) => a - b); };
  for (let i = 0; i < h.length - 1; i++) {
    const d = h[i + 1] - h[i];
    if (d > 0) {
      push(d);
      if (heap.length > ladders) {
        bricks -= heap.shift();
        if (bricks < 0) return i;
      }
    }
  }
  return h.length - 1;
}
class Solution {
    public int furthestBuilding(int[] h, int bricks, int ladders) {
        PriorityQueue<Integer> pq = new PriorityQueue<>();
        for (int i = 0; i < h.length - 1; i++) {
            int d = h[i + 1] - h[i];
            if (d > 0) {
                pq.offer(d);
                if (pq.size() > ladders) {
                    bricks -= pq.poll();
                    if (bricks < 0) return i;
                }
            }
        }
        return h.length - 1;
    }
}
int furthestBuilding(vector<int>& h, int bricks, int ladders) {
    priority_queue<int, vector<int>, greater<>> pq;
    for (int i = 0; i < (int)h.size() - 1; i++) {
        int d = h[i + 1] - h[i];
        if (d > 0) {
            pq.push(d);
            if ((int)pq.size() > ladders) {
                bricks -= pq.top(); pq.pop();
                if (bricks < 0) return i;
            }
        }
    }
    return h.size() - 1;
}
Time: O(n log L) Space: O(L)