-
Notifications
You must be signed in to change notification settings - Fork 41
/
solution.ts
76 lines (68 loc) · 1.95 KB
/
solution.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
function findMaximizedCapital (k: number, w: number, profits: number[], capitals: number[]): number {
const profitWithCapital = profits.map((profit, index) => {
return {
profit,
capital: capitals[index],
};
}).sort((a, b) => a.capital - b.capital);
const heap:number[] = [];
let index = 0;
while (index < profitWithCapital.length && profitWithCapital[index].capital <= w) {
heap.push(profitWithCapital[index++].profit);
}
const swap = (i:number, j:number) => {
const tmp = heap[i];
heap[i] = heap[j];
heap[j] = tmp;
};
const down = (pIndex:number) => {
while (2 * pIndex + 1 < heap.length) {
let cIndex = 2 * pIndex + 1;
if (cIndex + 1 < heap.length && heap[cIndex + 1] > heap[cIndex]) {
cIndex++;
}
if (heap[cIndex] > heap[pIndex]) {
swap(pIndex, cIndex);
pIndex = cIndex;
} else {
break;
}
}
};
const up = (cIndex:number) => {
while (cIndex > 0) {
const pIndex = (cIndex - 1) >> 1;
if (heap[cIndex] > heap[pIndex]) {
swap(cIndex, pIndex);
cIndex = pIndex;
} else {
break;
}
}
};
if (heap.length === 0) {
return w;
}
if (heap.length > 1) {
for (let i = (heap.length - 2) >> 1; i > -1; i--) {
down(i);
}
}
while (k > 0) {
if (heap.length === 0) {
break;
}
w += heap[0];
heap[0] = heap[heap.length - 1];
heap.pop();
if (heap.length) {
down(0);
}
while (index < profitWithCapital.length && profitWithCapital[index].capital <= w) {
heap.push(profitWithCapital[index++].profit);
up(heap.length - 1);
}
k--;
}
return w;
}