时间轴

2025-12-08

init


题目:

堆排序,每次把小于等于当前资本的所有利润放入堆中,取最大值,然后更新资本,重复以上操作,直到进行了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
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
#include <vector>
#include <unordered_map>
#include <utility>
#include <algorithm>
#include <queue>

using std::vector;
using std::unordered_map;
using std::pair;
using std::priority_queue;

class Solution {
public:
int findMaximizedCapital(int k, int w, vector<int> &profits,
vector<int> &capital)
{
int n = profits.size();
int i, selected = 0;

vector<pair<int, int> > prof2cap;

for (i = 0; i < n; i++) {
prof2cap.push_back({ profits[i], capital[i] });
}

std::sort(prof2cap.begin(), prof2cap.end(),
[](pair<int, int> &l, pair<int, int> &r) {
return l.second < r.second;
});
priority_queue<int> profit_heap;

i = 0;
while (k--) {
// 把所有capital小于w的加入堆
while (i < n && prof2cap[i].second <= w) {
profit_heap.push(prof2cap[i++].first);
}

if (profit_heap.empty()) {
break;
}

w += profit_heap.top();
profit_heap.pop();
}
return w;
}
};