[LeetCode] Maximize the Profit as the Salesman

2830. Maximize the Profit as the Salesman

You are given an integer n representing the number of houses on a number line, numbered from 0 to n - 1.

Additionally, you are given a 2D integer array offers where offers[i] = [starti, endi, goldi], indicating that ith buyer wants to buy all the houses from starti to endi for goldi amount of gold.

As a salesman, your goal is to maximize your earnings by strategically selecting and selling houses to buyers.

Return the maximum amount of gold you can earn.

Note that different buyers can’t buy the same house, and some houses may remain unsold.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
class Solution {
public:
int maximizeTheProfit(int n, vector<vector<int>>& offers) {
priority_queue<pair<int, int>, vector<pair<int, int>>, greater<pair<int, int>>> q;
int res = 0, ma = 0;
sort(begin(offers), end(offers));
for(int i = 0; i < offers.size(); i++) {
int l = offers[i][0], r = offers[i][1], c = offers[i][2];
while(q.size() and q.top().first < l) {
ma = max(ma, q.top().second);
q.pop();
}
res = max(res, ma + c);
q.push({r,ma + c});
}
while(q.size()) {
res = max(res, q.top().second); q.pop();
}
return res;
}
};

Author: Song Hayoung
Link: https://songhayoung.github.io/2023/08/20/PS/LeetCode/maximize-the-profit-as-the-salesman/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.