1642. Furthest Building You Can Reach

T: O(n + klogk)
S: O(k)
```java
class Solution {
    public int furthestBuilding(int[] heights, int bricks, int ladders) {
        Queue<Integer> minHeap = new PriorityQueue<>();
        for (int i = 0; i < heights.length - 1; i++) {
            if (heights[i+1] - heights[i] > 0) {
                int diff = heights[i+1] - heights[i];
                minHeap.offer(diff);
                if (minHeap.size() > ladders) {
                    bricks -= minHeap.poll();
                }
                if (bricks < 0) {
                    return i;
                }
            }
        }
        return heights.length - 1;
    }
}

/**
T: O(n + klogk)
S: O(k)

[1,5,1,2,3,4,10000]
bricks = 4
ladders = 1

    1 ladder can preserve to use
  4   1 1 1  9996
      

use a min heap

if there is a diff
add to heap
if (heap.size > ladders)
means we need to use brick, but we always use a min one

    1 ladder can preserve to use
  4   1 1 1  9996
      b b b. here is brick < 0 so return i
  in this way, we can assure, ladder is using by the larger one diff!!    


heights = [4,2,7,6,9,14,12], bricks = 5, ladders = 1
Output: 4
         4
         x
[4,2,7,6,9,14,12]
    5   3. 5(can't')
       5-3 = 2 
 */
```

Last updated