502. IPO
HardSolutions in Python, Java, C++, TypeScript
Read the full problem statement on LeetCode and try it first. Below is how to approach it in an interview, followed by a complete answer in each language.
Approach
The problem asks us to maximize our final capital by selecting at most k projects from a given list. Each project has a specific profit and requires a minimum capital to start. Our capital increases by the project's profit upon completion.
Solution
IPO in Python
import heapq
class Solution:
def findMaximizedCapital(self, k: int, w: int, profits: list[int], capital: list[int]) -> int:
n = len(profits)
# Create a list of projects with (capital, profit) and sort by capital.
projects = sorted(zip(capital, profits))
# Max-heap to store profits of affordable projects.
# Python's heapq is a min-heap, so we store negative profits to simulate a max-heap.
max_heap = []
project_idx = 0
# Iterate up to k times to select projects.
for _ in range(k):
# Add all projects that we can afford with the current capital `w` to the max-heap.
while project_idx < n and projects[project_idx][0] <= w:
heapq.heappush(max_heap, -projects[project_idx][1])
project_idx += 1
# If the heap is empty, it means there are no affordable projects left.
if not max_heap:
break
# Greedily choose the project with the highest profit.
# Pop from the min-heap (which gives the smallest negative value)
# and negate it back to get the maximum positive profit.
w += -heapq.heappop(max_heap)
return w
IPO in Java
class Solution {
public int findMaximizedCapital(int k, int w, int[] profits, int[] capital) {
int n = profits.length;
int[][] projects = new int[n][2];
for (int i = 0; i < n; i++) {
projects[i][0] = capital[i];
projects[i][1] = profits[i];
}
// Sort projects based on the capital required.
Arrays.sort(projects, (a, b) -> Integer.compare(a[0], b[0]));
// Max-heap to store profits of all affordable projects.
// Java's PriorityQueue is a min-heap by default, so we use a custom comparator for a max-heap.
PriorityQueue<Integer> maxHeap = new PriorityQueue<>((a, b) -> b - a);
int projectIndex = 0;
// We can perform at most k projects.
for (int i = 0; i < k; i++) {
// Add all projects that we can afford with the current capital `w` to the max-heap.
while (projectIndex < n && projects[projectIndex][0] <= w) {
maxHeap.add(projects[projectIndex][1]);
projectIndex++;
}
// If the heap is empty, it means there are no affordable projects left.
if (maxHeap.isEmpty()) {
break;
}
// Greedily choose the project with the highest profit.
w += maxHeap.poll();
}
return w;
}
}
IPO in C++
class Solution {
public:
int findMaximizedCapital(int k, int w, vector<int>& profits, vector<int>& capital) {
int n = profits.size();
vector<pair<int, int>> projects;
for (int i = 0; i < n; ++i) {
projects.push_back({capital[i], profits[i]});
}
// Sort projects based on the capital required.
sort(projects.begin(), projects.end());
// Max-heap to store profits of all affordable projects.
priority_queue<int> max_heap;
int project_idx = 0;
// We can perform at most k projects.
for (int i = 0; i < k; ++i) {
// Add all projects that we can afford with the current capital `w` to the max-heap.
while (project_idx < n && projects[project_idx].first <= w) {
max_heap.push(projects[project_idx].second);
project_idx++;
}
// If the heap is empty, it means there are no affordable projects left.
if (max_heap.empty()) {
break;
}
// Greedily choose the project with the highest profit.
w += max_heap.top();
max_heap.pop();
}
return w;
}
};
IPO in TypeScript
function findMaximizedCapital(k: number, w: number, profits: number[], capital: number[]): number {
// A minimal MaxPriorityQueue implementation to support the algorithm.
class MaxPriorityQueue {
private heap: number[] = [];
private compare(a: number, b: number): boolean {
return a > b;
}
private getParentIndex(i: number): number { return Math.floor((i - 1) / 2); }
private getLeftChildIndex(i: number): number { return 2 * i + 1; }
private getRightChildIndex(i: number): number { return 2 * i + 2; }
private swap(i: number, j: number): void {
[this.heap[i], this.heap[j]] = [this.heap[j], this.heap[i]];
}
private siftUp(i: number): void {
let parentIndex = this.getParentIndex(i);
while (i > 0 && this.compare(this.heap[i], this.heap[parentIndex])) {
this.swap(i, parentIndex);
i = parentIndex;
parentIndex = this.getParentIndex(i);
}
}
private siftDown(i: number): void {
let maxIndex = i;
const leftIndex = this.getLeftChildIndex(i);
const rightIndex = this.getRightChildIndex(i);
const size = this.size();
if (leftIndex < size && this.compare(this.heap[leftIndex], this.heap[maxIndex])) {
maxIndex = leftIndex;
}
if (rightIndex < size && this.compare(this.heap[rightIndex], this.heap[maxIndex])) {
maxIndex = rightIndex;
}
if (i !== maxIndex) {
this.swap(i, maxIndex);
this.siftDown(maxIndex);
}
}
public push(value: number): void {
this.heap.push(value);
this.siftUp(this.heap.length - 1);
}
public pop(): number | undefined {
if (this.size() === 0) return undefined;
if (this.size() === 1) return this.heap.pop();
const root = this.heap[0];
this.heap[0] = this.heap.pop()!;
this.siftDown(0);
return root;
}
public isEmpty(): boolean { return this.heap.length === 0; }
public size(): number { return this.heap.length; }
}
const n = profits.length;
const projects: {cap: number, pro: number}[] = [];
for (let i = 0; i < n; i++) {
projects.push({cap: capital[i], pro: profits[i]});
}
// Sort projects by capital required.
projects.sort((a, b) => a.cap - b.cap);
// Max-heap to store profits of affordable projects.
const maxHeap = new MaxPriorityQueue();
let projectIndex = 0;
// We can perform at most k projects.
for (let i = 0; i < k; i++) {
// Add all projects that we can afford with the current capital `w` to the max-heap.
while (projectIndex < n && projects[projectIndex].cap <= w) {
maxHeap.push(projects[projectIndex].pro);
projectIndex++;
}
// If the heap is empty, it means there are no affordable projects left.
if (maxHeap.isEmpty()) {
break;
}
// Greedily choose the project with the highest profit.
w += maxHeap.pop()!;
}
return w;
}
More Hard LeetCode answers
Preparing for interviews beyond LeetCode? Practise system design, SQL and behavioral questions with an in-browser runner on KatInterview.
LeetCode is a trademark of LeetCode LLC. KatInterview is not affiliated with LeetCode.