IPO
描述
-
假设 力扣(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 <= 1 0 5 10^5 105
- 0 <= w <= 1 0 9 10^9 109
- n == profits.length
- n == capital.length
- 1 <= n <= 1 0 5 10^5 105
- 0 <= profits[i] <= 1 0 4 10^4 104
- 0 <= capital[i] <= 1 0 9 10^9 109
Typescript 版算法实现
1 ) 方案1: 利用堆的贪心算法
class Heap {
heap: any[] = [];
constructor(private compareFn: (a: any, b: any) => boolean) {}
swap(i: number, j: number): void {
[this.heap[i], this.heap[j]] = [this.heap[j], this.heap[i]];
}
getParentIndex(i: number): number {
return Math.floor((i - 1) / 2);
}
getLeftIndex(pi: number): number {
return (pi << 1) + 1;
}
getRightIndex(pi: number): number {
return (pi << 1) + 2;
}
peak(): any | undefined {
return this.heap[0];
}
size(): number {
return this.heap.length;
}
insert(value: any): void {
this.heap.push(value);
this.shiftUp(this.size() - 1);
}
pop(): any | undefined {
if (this.size() === 0) return undefined;
if (this.size() === 1) return this.heap.pop();
const first = this.heap[0];
this.heap[0] = this.heap.pop()!;
this.shiftDown(0);
return first;
}
shiftUp(i: number): void {
while (i > 0) {
const pi = this.getParentIndex(i);
if (!this.compareFn(this.heap[pi], this.heap[i])) break;
this.swap(pi, i);
i = pi;
}
}
shiftDown(pi: number): void {
let largest = pi;
const li = this.getLeftIndex(pi);
const ri = this.getRightIndex(pi);
if (li < this.size() && this.compareFn(this.heap[largest], this.heap[li])) {
largest = li;
}
if (ri < this.size() && this.compareFn(this.heap[largest], this.heap[ri])) {
largest = ri;
}
if (largest !== pi) {
this.swap(pi, largest);
this.shiftDown(largest);
}
}
}
class MaxHeap extends Heap {
constructor() {
super((a: number, b: number) => a < b);
}
}
function findMaximizedCapital(k: number, w: number, profits: number[], capital: number[]): number {
const n = profits.length;
let curr = 0;
const arr: [number, number][] = [];
for (let i = 0; i < n; ++i) {
arr.push([capital[i], profits[i]]);
}
arr.sort((a, b) => a[0] - b[0]);
const pq = new MaxHeap();
for (let i = 0; i < k; ++i) {
while (curr < n && arr[curr][0] <= w) {
pq.insert(arr[curr][1]);
curr++;
}
if (pq.size() > 0) {
w += pq.pop()!;
} else {
break;
}
}
return w;
}
3639



被折叠的 条评论
为什么被折叠?



