ps
99클럽 코테스터디 23일차 TIL IPO
nastorond
2024. 8. 14. 00:03
IPO
LeetCode Hard Greedy
문제설명
Suppose LeetCode will start its IPO soon. In order to sell a good price of its shares to Venture Capital, LeetCode would like to work on some projects to increase its capital before the IPO. Since it has limited resources, it can only finish at most k distinct projects before the IPO. Help LeetCode design the best way to maximize its total capital after finishing at most k distinct projects.
You are given n projects where the ith project has a pure profit profits[i] and a minimum capital of capital[i] is needed to start it.
Initially, you have w capital. When you finish a project, you will obtain its pure profit and the profit will be added to your total capital.
Pick a list of at most k distinct projects from given projects to maximize your final capital, and return the final maximized capital.
The answer is guaranteed to fit in a 32-bit signed integer.
k 만큼의 프로젝트를 진행할 수 있을 때, w 가 최대가 될 수 있는 경우의 수를 계산해 최대의 이익을 내면 되는 문제였다.
w 는 프로젝트가 끝난 후에 해당 프로젝트의 profits[idx] 만큼 늘어날 수 있다.
문제 풀이
처음에는 priority_queue 를 두개 사용해서 접근했다.
struct CustomCompare {
bool operator()(const pair<int, int>& a, const pair<int, int>& b) {
if (a.first == b.first) {
return a.second > b.second;
}
return a.first < b.first;
}
};
int findMaximizedCapital(int k, int w, vector<int>& profits, vector<int>& capital) {
int n = profits.size();
priority_queue<pair<int, int>, vector<pair<int, int>>, CustomCompare> pq, sub_pq;
// init
for (int i=0; i<n; i++) {
pq.push(make_pair(profits[i], capital[i]));
}
while(k > 0) {
bool is_selected = false;
while (!pq.empty() && k > 0) {
pair<int, int> tmp = pq.top(); pq.pop();
if (w >= tmp.second) {
w += tmp.first;
k -= 1;
is_selected = true;
} else sub_pq.push(tmp);
}
if (k < 1) break;
while (!sub_pq.empty() && k > 0) {
pair<int, int> tmp = sub_pq.top(); sub_pq.pop();
if (w >= tmp.second) {
w += tmp.first;
k -= 1;
is_selected = true;
} else pq.push(tmp);
}
if (!is_selected) return w;
}
return w;
}
두개의 우선순위 큐에 profit 이 크면서 capital 이 작은 순서대로 넣어줬더니 잘 안됐다.
1시간 정도 디버깅 한 끝에 Discuss 에 들어가니 명쾌하게 설명된 답이 있었다.
capital 을 기준으로 정렬하고, 정렬된 값들을 놓고 순서대로 Maxheap 에 넣어주며 답을 구할 수 있었다.
코드
class Solution {
public:
int findMaximizedCapital(int k, int w, vector<int>& profits, vector<int>& capital) {
int n = profits.size();
vector<pair<int, int>> li;
for (int i=0; i<n; i++) {
li.push_back(make_pair(capital[i], profits[i]));
}
sort(li.begin(), li.end());
priority_queue<int> pq;
int idx = 0;
for(int j=0; j<k; j++) {
while (idx < n && li[idx].first <= w) {
pq.push(li[idx].second);
idx++;
}
if (pq.empty()) break;
w += pq.top();
pq.pop();
}
return w;
}
};
회고
뭔가 될 것 같은데 안되니까 답답해서 디버깅을 더 오래 했던 것 같다.
LeetCode 의 Hard 는 뭔가 남다른 것 같다.