Algo-Sim › Heaps & Priority Queues
IPO
Hard · Heaps & Priority Queues · step through it in Java, Python and C++ on your own input
Two heaps: projects locked by capital (min-heap) move into a profit max-heap as capital grows; each round takes the best affordable profit.
Problem
You start with capital w and may finish at most k distinct projects. Project i needs at least capital[i] to start and adds profits[i] to your capital when done. Choose projects to maximise your final capital, and return it.
Constraints
- 1 ≤ k ≤ 10⁵
- 0 ≤ w ≤ 10⁹
- 1 ≤ n ≤ 10⁵, profits and capital have length n
- 0 ≤ profits[i] ≤ 10⁴, 0 ≤ capital[i] ≤ 10⁹
Edge cases to test
- k larger than the number of projects
- No affordable project at the start: stop early
- Projects with zero profit
Follow-up questions
- Why is greedy on profit optimal?
- Capital never decreases, so taking the most profitable affordable project can only unlock more projects than any other choice.
- What is the cost?
- O((n + k) log n): each project enters and leaves each heap at most once.
Solution
Java
public int findMaximizedCapital(int k, int w, int[] profits, int[] capital) {
PriorityQueue<int[]> locked = new PriorityQueue<>((a, b) -> a[0] - b[0]);
PriorityQueue<Integer> ready = new PriorityQueue<>(Collections.reverseOrder());
for (int i = 0; i < profits.length; i++) {
locked.offer(new int[] {capital[i], profits[i]});
}
for (int round = 0; round < k; round++) {
while (!locked.isEmpty() && locked.peek()[0] <= w) {
ready.offer(locked.poll()[1]);
}
if (ready.isEmpty()) break;
w += ready.poll();
}
return w;
}Python
import heapq
def find_maximized_capital(k, w, profits, capital):
locked = [] # (capital, profit): cheapest to start on top
ready = [] # negated profits: the best affordable on top
for c, p in zip(capital, profits):
heapq.heappush(locked, (c, p))
for _ in range(k):
while locked and locked[0][0] <= w:
heapq.heappush(ready, -heapq.heappop(locked)[1])
if not ready:
break
w -= heapq.heappop(ready)
return wC++
#include <bits/stdc++.h>
using namespace std;
class Solution {
public:
int findMaximizedCapital(int k, int w, vector<int> &profits, vector<int> &capital) {
priority_queue<pair<int, int>, vector<pair<int, int>>, greater<>> locked;
priority_queue<int> ready;
for (int i = 0; i < int(profits.size()); i++) {
locked.push({capital[i], profits[i]});
}
for (int round = 0; round < k; round++) {
while (!locked.empty() && locked.top().first <= w) {
ready.push(locked.top().second);
locked.pop();
}
if (ready.empty())
break;
w += ready.top();
ready.pop();
}
return w;
}
};
More Heaps & Priority Queues problems
- Kth Largest Element in an Array (Medium)
- Kth Largest Element in a Stream (Easy)
- Merge K Sorted Lists (Hard)
- Find Median from Data Stream (Hard)
- Find K Pairs with Smallest Sums (Medium)
- Heap Sort (Build Heap + Sift Down) (Medium)
- Last Stone Weight (Easy)
- K Closest Points to Origin (Medium)
- Top K Frequent Words (Medium)
- Reorganize String (Medium)