Leetcode-1642

Furthest Building You Can Reach

Time complexity: $O(n\log k)$

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
#include <iostream>
#include <vector>
#include <queue>

class Solution {
public:
    int furthestBuilding(std::vector<int>& heights, int bricks, int ladders) {
        int n = heights.size();
        std::priority_queue<int, std::vector<int>, std::greater<int>> pq;
        
        for (int i = 0; i < n - 1; ++i) {
            int diff = heights[i + 1] - heights[i];
            if (diff > 0) {
                pq.push(diff);
                if (pq.size() > ladders) {
                    bricks -= pq.top();
                    pq.pop();
                }
                if (bricks < 0) {
                    return i;
                }
            }
        }
        return n - 1;
    }
};

Leetcode-1642

Licensed under CC BY-NC-SA 4.0