【題解】LeetCode 1642. Furthest Building You Can Reach

【題目敘述】https://leetcode.com/problems/furthest-building-you-can-reach/

class Solution {
public:
    int furthestBuilding(vector<int>& h, int b, int l) {
        priority_queue <int> pq;
        for (int i = 1; i < h.size(); i++){
            int gap = h[i]-h[i-1];
            if (gap <= 0) continue;
            if (gap <= b){
                pq.push(gap);
                b -= gap;
            }
            else{
                pq.push(gap);
                b -= gap;
                while (l && b < 0){
                    b += pq.top();
                    pq.pop();
                    l--;
                }
                if (b < 0) return i-1;
            }
        }
        return h.size()-1;
    }
};
分享本文 Share with friends