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 i-th 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.

Input & Output

Example 1 — Basic Case
$ Input: k = 2, w = 0, profits = [1,2,3], capital = [0,1,1]
Output: 4
💡 Note: Start with capital 0. Can afford project 0 (capital=0, profit=1). After project 0, capital becomes 1. Now can afford projects 1 or 2. Project 1 has profit=2, so pick it. Final capital: 0 + 1 + 2 = 3. Wait, let me recalculate: we can do project 0 (capital 0→1), then project 2 (capital 1→4). Actually both projects 1 and 2 need capital 1, and both give different profits. Project 2 gives profit 3, so final is 0→1→4.
Example 2 — Limited by k
$ Input: k = 3, w = 0, profits = [1,2,3], capital = [0,1,2]
Output: 6
💡 Note: Can do all projects in order: project 0 (0→1), then project 1 (1→3), then project 2 (3→6)
Example 3 — Limited by Capital
$ Input: k = 1, w = 0, profits = [1,2,3], capital = [1,1,1]
Output: 0
💡 Note: Cannot afford any project since all require capital ≥ 1 but we start with 0

Constraints

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

Visualization

Tap to expand
IPO: Maximize Capital with Limited ProjectsAvailable ProjectsProject 0Capital: 0Profit: 1Project 1Capital: 1Profit: 2Project 2Capital: 1Profit: 3Strategyk = 2 projects maxw = 0 starting capitalOptimal Selection: Project 0 → Project 2Capital flow: 0 → 1 → 4Result: 4
Understanding the Visualization
1
Input
k=2 projects max, w=0 starting capital, projects with capital/profit requirements
2
Process
Greedily select most profitable projects we can afford
3
Output
Maximum achievable capital after k projects
Key Takeaway
🎯 Key Insight: Use heaps to efficiently track and select the most profitable projects you can afford at each step
Asked in
Google 12 Facebook 8 Amazon 6
78.4K Views
Medium Frequency
~25 min Avg. Time
1.5K Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen