leetcode-502-IPO
[博客链接]
[题目链接]
[github地址]
[题目描述]
假设 力扣(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
提示:
- 1 <= k <= 105
- 0 <= w <= 109
- n == profits.length
- n == capital.length
- 1 <= n <= 105
- 0 <= profits[i] <= 104
- 0 <= capital[i] <= 109
思路一:贪心法
- 贪心法的证明用归纳法证明
- 假设我们当前做项目成本范围内利润为c,当前所能选的项目最大利润为max,当前资产为w
- 可得c+w <= max+w
- 因此选择max会使w最大
- 同时因为当前总资产w并不会因为选择项目而改变,所以也就是说选择max并不会使结果变差
- 所以贪心法可以求出最优解
- 定义一个优先队列存入利润最大的索引,比较当前成本和总资产的关系,如果满足就做,不满足弹出队列
- 定义了一个undo列表,表示为选择的项目,每次重新放入堆中
- 时间有点长1117ms
public int findMaximizedCapital(int k, int w, int[] profits, int[] capital) {
PriorityQueue<Integer> priorityQueue = new PriorityQueue<>(new Comparator<Integer>() {
@Override
public int compare(Integer o1, Integer o2) {
return profits[o2] - profits[o1];
}
});
for (int i = 0; i < profits.length; i++) {
priorityQueue.add(i);
}
Stack<Integer> undo = new Stack<>();
int step = 0;
while (step < k && !priorityQueue.isEmpty()) {
int index = priorityQueue.poll();
if (w >= capital[index]) {
w += profits[index];
step++;
while (!undo.isEmpty()) {
priorityQueue.add(undo.pop());
}
continue;
}
undo.add(index);
}
return w;
}
- 时间复杂度O()
- 空间复杂度O(n)
思路二:思路一的优化
- 思路一主要的消耗时间在于undo的重新入队
- 本体可以通过先将数组根据成本排序,然后满足成本的项目入堆,这样即可减少重复入队的计算次数
public int findMaximizedCapital(int k, int w, int[] profits, int[] capital) {
PriorityQueue<Integer> priorityQueue = new PriorityQueue<>(new Comparator<Integer>() {
@Override
public int compare(Integer o1, Integer o2) {
return o2 - o1;
}
});
List<int[]> undo = new ArrayList<>();
for (int i = 0; i < profits.length; i++) {
undo.add(new int[]{capital[i], profits[i]});
}
Collections.sort(undo, (a, b) -> (a[0] - b[0]));
int step = 0, i = 0;
while (step < k) {
while (i < profits.length && undo.get(i)[0] <= w) {
priorityQueue.add(undo.get(i)[1]);
i++;
}
if (priorityQueue.isEmpty()) {
break;
}
w += priorityQueue.poll();
step++;
}
return w;
}
- 时间复杂度O()
- 空间复杂度O(n)