Back to blog
Dec 10, 2024
4 min read

LeetCode 502: IPO

Leetcode 502: IPO solution in Python

Problem Description

LeetCode Problem 502

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

 

Constraints:

  • 1 <= k <= 105
  • 0 <= w <= 109
  • n == profits.length
  • n == capital.length
  • 1 <= n <= 105
  • 0 <= profits[i] <= 104
  • 0 <= capital[i] <= 109

Difficulty: Hard

Tags: array, greedy, sorting, heap (priority queue)

Rating: 93.59%

Solution Approach

The optimal solution uses a combination of sorting and a max heap (priority queue), following a greedy approach:

  1. Sort Projects by Capital: First, we sort all projects by their capital requirements. This allows us to efficiently track which projects become available as our capital increases.

  2. Use Max Heap for Available Projects: We maintain a max heap of profits for all projects that we can currently afford. This ensures we always choose the most profitable project among the available ones.

  3. Iterative Selection: For each of the k iterations:

    • Add all newly affordable projects to the max heap
    • Select the most profitable project from the heap
    • Update our current capital

Here’s the solution with detailed explanations:

class Solution:
    def findMaximizedCapital(self, k: int, w: int, profits: List[int], capital: List[int]) -> int:
        projects = list(zip(capital, profits))
        projects.sort()  # Sort by capital requirements (first element of each pair)
        n = len(projects)
        curr_capital = w
        
        # Max heap to store profits of available projects
        # Using negative values since Python has min heap by default
        available_projects = []
        p_idx = 0
        
        for _ in range(k):
            # Add all projects that we can now afford to the heap
            while p_idx < n and projects[p_idx][0] <= curr_capital:
                heapq.heappush(available_projects, -projects[p_idx][1])
                p_idx += 1
            
            # If no projects are available, we're done
            if not available_projects:
                break
                
            # Take the most profitable project
            curr_capital += -heapq.heappop(available_projects)
            
        return curr_capital

Complexity Analysis

The solution has the following complexity characteristics:

  • Time Complexity: O(nlogn+klogn)O(nlogn + klogn)

    • Sorting projects: O(nlogn)O(nlogn)
    • For each of k iterations:
      • Heap operations: O(logn)O(logn)
      • Each project can be added to heap once: O(nlogn)O(nlogn) amortized
  • Space Complexity: O(n)O(n)

    • Storage for the projects array and heap

Example Walkthrough

Let’s trace through Example 1:

k = 2, w = 0, profits = [1,2,3], capital = [0,1,1]
  1. Initial state:

    • Current capital = 0
    • Sorted projects: [(0,1), (1,2), (1,3)]
  2. First iteration:

    • Available projects: Only project 0 (requires 0 capital)
    • Choose project 0, profit = 1
    • New capital = 1
  3. Second iteration:

    • Available projects: Both project 1 and 2 (both require 1 capital)
    • Choose project 2 (profit 3 > profit 2)
    • Final capital = 4

This demonstrates how the greedy approach of always choosing the most profitable available project leads to the optimal solution.