算法作业12

来源:互联网 发布:从程序员到架构师 pdf 编辑:程序博客网 时间:2024/06/17 12:31

题目地址: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
原创粉丝点击