Featured image of post IPO

IPO

502.IPO

分析

  1. 项目排序

    • 将每个项目的启动资本和利润配对,并按照启动资本排序
  2. 动态选择

    • 将当前资本 w 可以启动的所有项目的利润放入最大堆
    • 从堆中选择一个利润最大的项目并完成,更新当前资本
  3. 退出条件

    • 如果没有可以选择的项目(即堆为空),或者已经完成了 k 个项目,就可以退出

时间复杂度

  • 排序项目数组:O(nlogn)
  • 每次操作通过堆插入或弹出元素,最多需要 O(logn) 时间,因此 k 次操作的复杂度是 O(klogn)

总时间复杂度 O(nlogn)

空间复杂度

空间复杂度为 O(n)

C++代码

 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
class Solution
{
public:
    int findMaximizedCapital(int k, int w, vector<int>& profits, vector<int>& capital)
    {
        int n = profits.size();
        std::vector<std::pair<int, int>> projects;

        // 将项目的启动资本和利润配对,并按启动资本排序
        for (int i = 0; i < n; ++i)
            projects.push_back({capital[i], profits[i]});
        std::sort(projects.begin(), projects.end());

        // 最大堆,用来存放前资本 w 可以启动的所有项目的利润
        std::priority_queue<int> heap;
        int i = 0;

        // 完成最多 k 个项目
        while (k--)
        {
            // 将所有可以启动的项目的利润加入堆
            while (i < n && projects[i].first <= w)
                heap.push(projects[i++].second);

            // 如果堆为空,表示没有可用的项目,退出
            if (heap.empty())
                break;

            // 从堆中选择利润最大的项目并完成
            w += heap.top();
            heap.pop();
        }

        return w;
    }
};
Nickname
Email
Website
0/500
0 comments
Built with Hugo
Theme Stack designed by Jimmy