IPO——LeetCode⑫
//原题链接https://leetcode.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 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.
Example 1:
Input: k=2, W=0, Profits=[1,2,3], Capital=[0,1,1]. Output: 4 Explanation: Since your initial capital is 0, you can only start the project indexed 0. After finishing it you will obtain profit 1 and your capital becomes 1. With capital 1, you can either start the project indexed 1 or the project indexed 2. Since you can choose at most 2 projects, you need to finish the project indexed 2 to get the maximum capital. Therefore, output the final maximized capital, which is 0 + 1 + 3 = 4.
Note:
You may assume all numbers in the input are non-negative integers.
The length of Profits array and Capital array will not exceed 50,000.
The answer is guaranteed to fit in a 32-bit signed integer. - 思路分析
//IPO首次公开招募
在有w本金的情况下,完成k个项目,在资本足够的情况下寻找最大利润,在做完k个项目或者资金不足结束。
直接法:类似于背包,都可以采用贪心思想,选取当前资本足够且获益最高的项目,依次迭代。 - 源码附录
class Solution { public class Node{ public int cost; public int profit; public Node(int p,int c){ profit = p; cost = c; } } public int findMaximizedCapital(int k, int W, int[] Profits, int[] Capital) { PriorityQueue<Node> minCost = new PriorityQueue<Node>(new Comparator<Node>(){ public int compare(Node n,Node m){ return n.cost-m.cost; } }); PriorityQueue<Node> maxProfit = new PriorityQueue<Node>(new Comparator<Node>(){ public int compare(Node n,Node m){ return m.profit-n.profit; } }); Node cur; for(int i=0;i<Capital.length;i++){ cur = new Node(Profits[i],Capital[i]); minCost.add(cur); } for(int i=0;i<k;i++){ //亲娘咧 一定要记得小堆为空的时候 找了N久 while (!minCost.isEmpty() && minCost.peek().cost <= W) { maxProfit.add(minCost.poll()); } if(maxProfit.isEmpty()){ return W; } W = W + maxProfit.poll().profit; } return W; } }
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 阿里最新开源QwQ-32B,效果媲美deepseek-r1满血版,部署成本又又又降低了!
· 开源Multi-agent AI智能体框架aevatar.ai,欢迎大家贡献代码
· Manus重磅发布:全球首款通用AI代理技术深度解析与实战指南
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
· AI技术革命,工作效率10个最佳AI工具