算法作业12

题目地址https://leetcode.com/problems/ipo/#/description
题目描述: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 several projects. For each project i, it has a pure profit Pi and a minimum capital of Ci is needed to start the corresponding project. 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.

To sum up, pick a list of at most k distinct projects from given projects to maximize your final capital, and output your final maximized capital.

我的代码

class Solution {
public:
    int findMaximizedCapital(int k, int W, vector<int>& Profits, vector<int>& Capital) {
        vector<int> cap;
        for(int i=0;i<Capital.size();i++){
            cap.push_back(i);
        }
        priority_queue<int> pro;

        while(k--){
            int i=0;
            while(i<cap.size()){
                if(Capital[cap[i]]<=W){
                    pro.push(Profits[cap[i]]);
                    cap.erase(cap.begin()+i);
                }
                else i++;
            }
            if(pro.empty()) break;
            else{
                W+=pro.top();
                pro.pop();
            }
        }
        return W;
    }
};

解题思路
该题目的意思是有n个项目,每个项目有利润p和启动资金c,现在你有资金w,你最多可以启动k个项目,求你最后的总资金的最大值。
因为只要当你的资金w大于c时你就可以启动这个项目,没有任何其他的约束。而且,你的资金增加的量就是你完成的项目的利润p。所以当你能够完成的项目有限时,选择你能够启动的项目中利润最大的即可。
在我的代码中,用cap保存所有不能启动的项目的索引,即项目的序号。然后用优先队列来保存所有的可以 启动的项目的利润,而已经完成的项目则不需要出现在我们的考虑中,直接pop即可。
循环k次,每次循环会遍历cap,将w改变之后新的可启动的项目利润加入Pro中。然后取pro的第一个值即可。所有复杂度为O(kn).

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值