넘치게 채우기

[LeetCode] 502. IPO 본문

PS/LeetCode

[LeetCode] 502. IPO

riveroverflow 2024. 6. 15. 10:46
728x90
반응형

https://leetcode.com/problems/ipo/description/

leetcode - IPO

문제 유형 : 우선순위 큐, 정렬

문제 난이도 : Hard

 

문제

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.

 

LeetCode가 상장을 한다고 해보자. LeetCode는 상장 전에 프로젝트들을 통해 자본을 키워야 한다.

profits[i]에는 i번째 프로젝트의 이익이, capital[i]는 i번째 프로젝트의 요구 자본이다.

 

처음에는 w만큼 주어진다. 프로젝트를 완료하면, 이익을 얻을 수 있다.

k번의 프로젝트가 가능하다.

가능한 최대 자본을 구하시오.

 

풀이

우선, 하나에 묶는다. projects[i] =  <capital[i], profits[i]>이렇게.

그 다음, projects를 정렬한다. capital기준 오름차순으로 해주면 된다.

 

그 뒤, 최대힙 우선순위큐를 만들어준다.

그리고, 다음 과정을 k번 반복한다:

projects에서 현재 자본으로 가능한 프로젝트들을 모두 골라서 이익만 우선순위 큐에 넣는다.

그뒤 우선순위큐의 최대값을 누적시키고, pop해준다.

 

코드

C++

class Solution {
public:
    int findMaximizedCapital(int k, int w, vector<int>& profits, vector<int>& capital) {
        int n = profits.size();
        vector<pair<int, int>> projects(n);
        
        for (int i = 0; i < n; ++i) {
            projects[i] = {capital[i], profits[i]};
        }
        
        sort(projects.begin(), projects.end());
        priority_queue<int> maxHeap;
        int current = 0;

        for (int i = 0; i < k; ++i) {
            while (current < n && projects[current].first <= w) {
                maxHeap.push(projects[current].second);
                current++;
            }

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

            w += maxHeap.top();
            maxHeap.pop();
        }

        return w;
    }
};
728x90
반응형