-
Notifications
You must be signed in to change notification settings - Fork 10
/
Problem_3_Maximise_Capital.java
42 lines (33 loc) · 1.54 KB
/
Problem_3_Maximise_Capital.java
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
package Heap;
// Problem Statement: Maximize Capital (hard)
// LeetCode Question: 502. IPO
import java.util.PriorityQueue;
public class Problem_3_Maximise_Capital {
public int findMaximumCapital(int[] capital, int[] profits,
int numberOfProjects, int initialCapital) {
int n = profits.length;
PriorityQueue<Integer> minCapitalHeap =
new PriorityQueue<>(n, (i1, i2) -> capital[i1] - capital[i2]);
PriorityQueue<Integer> maxProfitHeap =
new PriorityQueue<>(n, (i1, i2) -> profits[i2] - profits[i1]);
// insert all project capitals to a min-heap
for (int i = 0; i < n; i++)
minCapitalHeap.offer(i);
// let's try to find a total of 'numberOfProjects' best projects
int availableCapital = initialCapital;
for (int i = 0; i < numberOfProjects; i++) {
// find all projects that can be selected within the available capital and insert
// them in a max-heap
while (!minCapitalHeap.isEmpty()
&& capital[minCapitalHeap.peek()] <= availableCapital)
maxProfitHeap.add(minCapitalHeap.poll());
// terminate if we are not able to find any project that can be completed within
// the available capital
if (maxProfitHeap.isEmpty())
break;
// select the project with the maximum profit
availableCapital += profits[maxProfitHeap.poll()];
}
return availableCapital;
}
}