IPO LeetCode Solution

Last updated on March 2nd, 2025 at 02:40 pm

Here, we see an IPO LeetCode Solution. This Leetcode problem is solved using different approaches in many programming languages, such as C++, Java, JavaScript, Python, etc.

List of all LeetCode Solution

Topics

Greedy, Heap

Level of Question

Hard

IPO LeetCode Solution

IPO LeetCode Solution

1. Problem Statement

Suppose LeetCode will start its IPO soon. In order to sell a good price of its shares to Venture Capital, LeetCode would like to work on some projects to increase its capital before the IPO. Since it has limited resources, it can only finish at most k distinct projects before the IPO. Help LeetCode design the best way to maximize its total capital after finishing at most k distinct projects.

You are given n projects where the ith project has a pure profit profits[i] and a minimum capital of capital[i] is needed to start it.

Initially, you have w capital. When you finish a project, you will obtain its pure profit and the profit will be added to your total capital.

Pick a list of at most k distinct projects from given projects to maximize your final capital, and return the final maximized capital.

The answer is guaranteed to fit in a 32-bit signed integer.

Example 1:
Input: k = 2, w = 0, profits = [1,2,3], capital = [0,1,1]
Output: 4
Explanation: Since your initial capital is 0, you can only start the project indexed 0. After finishing it you will obtain profit 1 and your capital becomes 1. With capital 1, you can either start the project indexed 1 or the project indexed 2. Since you can choose at most 2 projects, you need to finish the project indexed 2 to get the maximum capital. Therefore, output the final maximized capital, which is 0 + 1 + 3 = 4.

Example 2:
Input: k = 3, w = 0, profits = [1,2,3], capital = [0,1,2]
Output: 6

2. Coding Pattern Used in Solution

The coding pattern used in this code is “Top ‘K’ Elements”. This pattern is commonly used when we need to process or retrieve the top K elements from a dataset, often using a heap (priority queue). In this problem, the goal is to maximize the capital by selecting up to K projects with the highest profits that can be started with the current available capital.

3. Code Implementation in Different Languages

3.1 IPO 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(n);
        for (int i = 0; i < n; i++) {
            projects[i] = {capital[i], profits[i]};
        }
        sort(projects.begin(), projects.end());
        int i = 0;
        priority_queue<int> maximizeCapital;
        while (k--) {
            while (i < n && projects[i].first <= w) {
                maximizeCapital.push(projects[i].second);
                i++;
            }
            if (maximizeCapital.empty())
                break;
            w += maximizeCapital.top();
            maximizeCapital.pop();
        }
        return w;
    }
};

3.2 IPO 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];
        }
        Arrays.sort(projects, (a, b) -> Integer.compare(a[0], b[0]));
        int i = 0;
        PriorityQueue<Integer> maximizeCapital = new PriorityQueue<>(Collections.reverseOrder());
        while (k-- > 0) {
            while (i < n && projects[i][0] <= w) {
                maximizeCapital.offer(projects[i][1]);
                i++;
            }
            if (maximizeCapital.isEmpty()) {
                break;
            }
            w += maximizeCapital.poll();
        }
        return w;
    }
}

3.3 IPO JavaScript

var findMaximizedCapital = function(k, w, profits, capital) {
    let projects = [];
    let heap = new MaxHeap();

    for(let i = 0; i < profits.length; i++){
        projects.push([profits[i], capital[i]]);
    }
    projects.sort((a, b) => a[1] - b[1]);
    let x = 0;
    while(projects[x] && projects[x][1] <= w){
        heap.add(projects[x][0]);
        x++;
    }
    while(heap.values.length > 0 && k > 0){
        w += heap.extractMax();
        k--;
        while(projects[x] && projects[x][1] <= w){
            heap.add(projects[x][0]);
            x++;
        }
    }
    return w;
};

class MaxHeap {
    constructor() {
        this.values = [];
    }
    parent(index) {
        return Math.floor((index - 1) / 2);
    }
    leftChild(index) {
        return (index * 2) + 1;
    }
    rightChild(index) {
        return (index * 2) + 2;
    }

    isLeaf(index) {
        return (
            index >= Math.floor(this.values.length / 2) && index <= this.values.length - 1
        )
    }
    swap(index1, index2) {
        [this.values[index1], this.values[index2]] = [this.values[index2], this.values[index1]];
    }

    heapifyDown(index) {
        if (!this.isLeaf(index)) {
            let leftChildIndex = this.leftChild(index),
                rightChildIndex = this.rightChild(index),
                largestIndex = index;
            if (this.values[leftChildIndex] > this.values[largestIndex]) {
                largestIndex = leftChildIndex;
            }
            if (this.values[rightChildIndex] >= this.values[largestIndex]) {
                largestIndex = rightChildIndex;
            }
            if (largestIndex !== index) {
                this.swap(index, largestIndex);
                this.heapifyDown(largestIndex);
            }
        }
    }

    heapifyUp(index) {
        let currentIndex = index,
            parentIndex = this.parent(currentIndex);
        while (currentIndex > 0 && this.values[currentIndex] > this.values[parentIndex]) {
            this.swap(currentIndex, parentIndex);
            currentIndex = parentIndex;
            parentIndex = this.parent(parentIndex);
        }
    }
    add(element) {
        this.values.push(element);
        this.heapifyUp(this.values.length - 1);
    }
    peek() {
        return this.values[0];
    }

    extractMax() {
        if(this.values.length === 1) return this.values.pop();
        if (this.values.length < 1) return 'heap is empty';
        const max = this.values[0];
        const end = this.values.pop();
        this.values[0] = end;
        this.heapifyDown(0);
        return max;
    }

    buildHeap(array) {
        this.values = array;
        for(let i = Math.floor(this.values.length / 2); i >= 0; i--){
            this.heapifyDown(i);
        }
    }
    print() {
        let i = 0;
        while (!this.isLeaf(i)) {
            console.log("PARENT:", this.values[i]);
            console.log("LEFT CHILD:", this.values[this.leftChild(i)]);
            console.log("RIGHT CHILD:", this.values[this.rightChild(i)]);
            i++;
        }      
    }
}

3.4 IPO Python

class Solution:
    def findMaximizedCapital(self, k, w, profits, capital):
        n = len(profits)
        projects = [(capital[i], profits[i]) for i in range(n)]
        projects.sort()
        i = 0
        maximizeCapital = []
        while k > 0:
            while i < n and projects[i][0] <= w:
                heapq.heappush(maximizeCapital, -projects[i][1])
                i += 1
            if not maximizeCapital:
                break
            w -= heapq.heappop(maximizeCapital)
            k -= 1
        return w

4. Time and Space Complexity

Time ComplexitySpace Complexity
C++O(n log n + k log n)O(n)
JavaO(n log n + k log n)O(n)
JavaScriptO(n log n + k log n)O(n)
PythonO(n log n + k log n)O(n)
  • Sorting projects takes O(n log n), and heap operations (push/pop) take O(log n) for up to k iterations.
  • The code efficiently selects up to K projects with the highest profits that can be started with the available capital, using a combination of sorting and a max-heap.
  • The overall complexity is driven by the sorting step and the heap operations.
Scroll to Top