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

Edge cases to test

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 w

C++

#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