​LeetCode刷题实战502:IPO

程序IT圈

共 2649字,需浏览 6分钟

 · 2022-01-23

算法的重要性,我就不多说了吧,想去大厂,就必须要经过基础知识和业务逻辑面试+算法面试。所以,为了提高大家的算法能力,这个公众号后续每天带大家做一道算法题,题目就从LeetCode上面选 !

今天和大家聊的问题叫做 IPO,我们先来看题面:
https://leetcode-cn.com/problems/ipo/


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)即将开始 IPO 。为了以更高的价格将股票卖给风险投资公司,力扣 希望在 IPO 之前开展一些项目以增加其资本。由于资源有限,它只能在 IPO 之前完成最多 k 个不同的项目。帮助 力扣 设计完成最多 k 个不同项目后得到最大总资本的方式。

给你 n 个项目。对于每个项目 i ,它都有一个纯利润 profits[i] ,和启动该项目需要的最小资本 capital[i] 。

最初,你的资本为 w 。当你完成一个项目时,你将获得纯利润,且利润将被添加到你的总资本中。

总而言之,从给定项目中选择 最多 k 个不同项目的列表,以 最大化最终资本 ,并输出最终可获得的最多资本。

答案保证在 32 位有符号整数范围内。

示例                         

示例 1:

输入:k = 2, w = 0, profits = [1,2,3], capital = [0,1,1]
输出:4
解释:
由于你的初始资本为 0,你仅可以从 0 号项目开始。
在完成后,你将获得 1 的利润,你的总资本将变为 1。
此时你可以选择开始 1 号或 2 号项目。
由于你最多可以选择两个项目,所以你需要完成 2 号项目以获得最大的资本。
因此,输出最后最大化的资本,为 0 + 1 + 3 = 4。

示例 2:

输入:k = 3, w = 0, profits = [1,2,3], capital = [0,1,2]
输出:6


解题

https://www.acwing.com/solution/leetcode/content/36257/

由于本题不减去成本,选择收益更大的一个项目一方面在当前轮会带来更大的收益,另一方面会增加下一轮的w,也就是增加下一轮可选项目的范围,属于双重利好,因此这个策略是没有问题的。(但是如果要减去成本就不一定了,因为当前收益更大的项目也许成本也更高)。

class Solution {
public:
    int findMaximizedCapital(int k, int w, vector<int>& Profits, vector<int>& Capital) {
        vectorint, int>> q;
        int st = w;
        int n = Profits.size();
        for (int i = 0; i < n; i ++ )
            q.push_back({Capital[i], Profits[i]});
        sort(q.begin(), q.end());
        priority_queue<int> heap;
        int i = 0, res = 0;
        while (k -- ) {
            while (i < n && w >= q[i].first)
                heap.push(q[i ++ ].second);
            if (heap.empty()) break;
            auto t = heap.top(); heap.pop();
            res += t;
            w += t;
        }
        return res + st;
    }
};


好了,今天的文章就到这里,如果觉得有所收获,请顺手点个在看或者转发吧,你们的支持是我最大的动力 。

上期推文:
LeetCode1-500题汇总,希望对你有点帮助!
LeetCode刷题实战501:二叉搜索树中的众数


浏览 11
点赞
评论
收藏
分享

手机扫一扫分享

举报
评论
图片
表情
推荐
点赞
评论
收藏
分享

手机扫一扫分享

举报