IPO — LeetCode 502 Python Solution
- Problem
- #502
- Pattern
- Heap / Priority Queue
- Reading time
- 3 min
- Source
- leetcode.com
The problem
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.
Example
- 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.
Python solution
class Solution:
def findMaximizedCapital(
self, k: int, w: int, profits: List[int], capital: List[int]
) -> int:
h1 = [(c, p) for c, p in zip(capital, profits)]
heapify(h1)
h2 = []
while k:
while h1 and h1[0][0] <= w:
heappush(h2, -heappop(h1)[1])
if not h2:
break
w -= heappop(h2)
k -= 1
return wComplexity
| Measure | Complexity |
|---|---|
| Time | O(n log n) |
| Space | O(1) to O(n) auxiliary |
Pattern: Heap / Priority Queue
Keep only the best k elements, or always pull the smallest, in log time. LeetCode 502. IPO is filed here because LeetCode tags it Heap (Priority Queue), which is the vocabulary this hub collects.
The heap / priority queue guide has the Python template for the pattern and the 163 LeetCode problems that use it.
Related problems
On a study list
This problem is on Top Interview 150.
Frequently asked questions
- How hard is LeetCode 502. IPO?
- LeetCode 502. IPO is rated Hard on LeetCode.
- What topics does LeetCode 502. IPO cover?
- LeetCode 502. IPO is tagged Greedy, Array, Sorting and Heap (Priority Queue) on LeetCode.