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
The key insight is to use a greedy approach with heaps: sort projects by capital requirement, then always pick the most profitable project you can currently afford. Best approach uses two heaps for O(n log n + k log n) time complexity.
Common Approaches
Approach
Time
Space
Notes
✓
Brute Force - Try All Combinations
O(n^k * k)
O(k)
Generate all possible combinations of k projects and find the one with maximum profit
Greedy with Two Heaps
O(n log n + k log n)
O(n)
Use min-heap for available projects and max-heap for profits to greedily select optimal projects
Brute Force - Try All Combinations — Algorithm Steps
Generate all combinations of k projects
For each combination, check if affordable in sequence
Track maximum achievable capital
Visualization
Tap to expand
Step-by-Step Walkthrough
1
Generate Combinations
Create all possible sets of k projects
2
Check Affordability
For each combination, verify we can afford projects in order
3
Find Maximum
Track the combination that gives highest final capital
Code -
solution.c — C
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int maxCapital;
void swap(int *a, int *b) {
int temp = *a;
*a = *b;
*b = temp;
}
void generatePermutations(int arr[], int start, int end, int k, int w, int profits[], int capital[]) {
if (start == end) {
int currentCapital = w;
int valid = 1;
// Try to execute all projects in this order
for (int i = 0; i <= end; i++) {
if (currentCapital >= capital[arr[i]]) {
currentCapital += profits[arr[i]];
} else {
valid = 0;
break;
}
}
if (valid && currentCapital > maxCapital) {
maxCapital = currentCapital;
}
return;
}
for (int i = start; i <= end; i++) {
swap(&arr[start], &arr[i]);
generatePermutations(arr, start + 1, end, k, w, profits, capital);
swap(&arr[start], &arr[i]);
}
}
void generateCombinations(int start, int remaining, int current[], int currentSize, int k, int w, int profits[], int capital[], int n) {
if (remaining == 0 || start == n) {
if (currentSize == 0) return;
// Try all permutations of current combination
int perm[currentSize];
for (int i = 0; i < currentSize; i++) {
perm[i] = current[i];
}
generatePermutations(perm, 0, currentSize - 1, k, w, profits, capital);
return;
}
// Include current project
if (currentSize < k) {
current[currentSize] = start;
generateCombinations(start + 1, remaining - 1, current, currentSize + 1, k, w, profits, capital, n);
}
// Skip current project
generateCombinations(start + 1, remaining, current, currentSize, k, w, profits, capital, n);
}
int solution(int k, int w, int profits[], int capital[], int n) {
maxCapital = w;
int current[k];
generateCombinations(0, k, current, 0, k, w, profits, capital, n);
return maxCapital;
}
int main() {
int k, w;
scanf("%d", &k);
scanf("%d", &w);
// Parse profits array
char line[1000];
scanf(" %[^\n]", line);
int profits[100], profitCount = 0;
char *token = strtok(line + 1, ",]"); // Skip '['
while (token) {
profits[profitCount++] = atoi(token);
token = strtok(NULL, ",]");
}
// Parse capital array
scanf(" %[^\n]", line);
int capital[100], capitalCount = 0;
token = strtok(line + 1, ",]"); // Skip '['
while (token) {
capital[capitalCount++] = atoi(token);
token = strtok(NULL, ",]");
}
int result = solution(k, w, profits, capital, profitCount);
printf("%d\n", result);
return 0;
}
Time & Space Complexity
Time Complexity
⏱️
O(n^k * k)
Generate C(n,k) combinations, each taking O(k) time to validate
n
2n
✓ Linear Growth
Space Complexity
O(k)
Store current combination of k projects
n
2n
✓ Linear Space
78.4K Views
MediumFrequency
~25 minAvg. Time
1.5K Likes
Ln 1, Col 1
Smart Actions
💡Explanation
AI Ready
💡 SuggestionTabto acceptEscto dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen
Algorithm Visualization
Pinch to zoom • Tap outside to close
Test Cases
0 passed
0 failed
3 pending
Select Compiler
Choose a programming language
Compiler list would appear here...
AI Editor Features
Header Buttons
💡
Explain
Get a detailed explanation of your code. Select specific code or analyze the entire file. Understand algorithms, logic flow, and complexity.
🔧
Fix
Automatically detect and fix issues in your code. Finds bugs, syntax errors, and common mistakes. Shows you what was fixed.
💡
Suggest
Get improvement suggestions for your code. Best practices, performance tips, and code quality recommendations.
💬
Ask AI
Open an AI chat assistant to ask any coding questions. Have a conversation about your code, get help with debugging, or learn new concepts.
Smart Actions (Slash Commands)
🔧
/fix Enter
Find and fix issues in your code. Detects common problems and applies automatic fixes.
💡
/explain Enter
Get a detailed explanation of what your code does, including time/space complexity analysis.
🧪
/tests Enter
Automatically generate unit tests for your code. Creates comprehensive test cases.
📝
/docs Enter
Generate documentation for your code. Creates docstrings, JSDoc comments, and type hints.
⚡
/optimize Enter
Get performance optimization suggestions. Improve speed and reduce memory usage.
AI Code Completion (Copilot-style)
👻
Ghost Text Suggestions
As you type, AI suggests code completions shown in gray text. Works with keywords like def, for, if, etc.
Tabto acceptEscto dismiss
💬
Comment-to-Code
Write a comment describing what you want, and AI generates the code. Try: # two sum, # binary search, # fibonacci
💡
Pro Tip: Select specific code before using Explain, Fix, or Smart Actions to analyze only that portion. Otherwise, the entire file will be analyzed.