#502
IPO
HardArrayGreedySortingHeap (Priority Queue)Greedy AlgorithmHeap (Priority Queue)
Approaches
Brute ForceOptimal
Complexity Comparison
| Brute Force | Optimal Solution★ | |
|---|---|---|
| Time | O(n²) | O(n log n + k log k) |
| Space | O(1) | O(n) |
💡
Intuition
Time O(n log n + k log k)Space O(n)
The optimal solution uses a greedy approach with a max-heap to always select the most profitable projects that can be started with the current capital. This ensures we maximize our capital efficiently.
⚙️
Algorithm
3 steps- 1Step 1: Pair the profits with their respective capital requirements and sort these pairs by capital.
- 2Step 2: Use a max-heap to keep track of the profits of projects that can be started with the current capital.
- 3Step 3: For up to k projects, extract the maximum profit from the heap and add it to the current capital.
solution.py14 lines
1# Full working Python code
2import heapq
3
4def maxCapitalOptimal(k, w, profits, capital):
5 projects = sorted(zip(capital, profits))
6 max_heap = []
7 index = 0
8 for _ in range(k):
9 while index < len(projects) and projects[index][0] <= w:
10 heapq.heappush(max_heap, -projects[index][1]) # Push negative profit for max-heap
11 index += 1
12 if max_heap:
13 w -= heapq.heappop(max_heap)
14 return wℹ
Complexity note: The time complexity is O(n log n) for sorting the projects and O(k log k) for managing the max-heap, making it efficient for larger inputs.
- 1Maximizing profit requires careful selection of projects based on current capital.
- 2Using a greedy approach with a max-heap allows for efficient selection of the most profitable projects.
Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.