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
✓
Binary Search
⏱️ Time: N/A
Space: N/A
Brute Force - Try All Combinations
⏱️ Time: O(n^k * k)
Space: O(k)
Try every possible subset of k projects, check if we have enough capital for each combination, and return the maximum achievable capital.
Greedy with Two Heaps
⏱️ Time: O(n log n + k log n)
Space: O(n)
Sort projects by capital requirement. Use a min-heap to track projects by capital and a max-heap to track available projects by profit. At each step, make available all affordable projects and pick the most profitable one.
Algorithm Steps — Algorithm Steps
Code -
solution.c — C
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
static int combinations[1000][10];
static int combCount;
static int permutations[5000][10];
static int permCount;
void generateCombinations(int* combo, int start, int depth, int n, int r) {
if (depth == r) {
for (int i = 0; i < r; i++) {
combinations[combCount][i] = combo[i];
}
combCount++;
return;
}
for (int i = start; i < n; i++) {
combo[depth] = i;
generateCombinations(combo, i + 1, depth + 1, n, r);
}
}
void swap(int* a, int* b) {
int temp = *a;
*a = *b;
*b = temp;
}
void generatePermutations(int* arr, int start, int len) {
if (start == len) {
for (int i = 0; i < len; i++) {
permutations[permCount][i] = arr[i];
}
permCount++;
return;
}
for (int i = start; i < len; i++) {
swap(&arr[start], &arr[i]);
generatePermutations(arr, start + 1, len);
swap(&arr[start], &arr[i]);
}
}
int* parseArray(char* str, int* size) {
// Remove brackets
if (str[0] == '[') str++;
int len = strlen(str);
if (str[len-1] == ']') str[len-1] = '\0';
if (strlen(str) == 0) {
*size = 0;
return NULL;
}
int* arr = malloc(100 * sizeof(int));
*size = 0;
char* token = strtok(str, ",");
while (token != NULL) {
arr[*size] = atoi(token);
(*size)++;
token = strtok(NULL, ",");
}
return arr;
}
int min(int a, int b) {
return a < b ? a : b;
}
int max(int a, int b) {
return a > b ? a : b;
}
int solution(int k, int w, int* profits, int* capital, int n) {
int maxCapital = w;
// Try all combinations of at most k projects
for (int r = 1; r <= min(k, n); r++) {
combCount = 0;
int combo[10];
generateCombinations(combo, 0, 0, n, r);
for (int c = 0; c < combCount; c++) {
permCount = 0;
int tempCombo[10];
for (int i = 0; i < r; i++) {
tempCombo[i] = combinations[c][i];
}
generatePermutations(tempCombo, 0, r);
for (int p = 0; p < permCount; p++) {
int currentCapital = w;
int valid = 1;
// Try to execute all projects in this order
for (int i = 0; i < r; i++) {
int projIdx = permutations[p][i];
if (currentCapital >= capital[projIdx]) {
currentCapital += profits[projIdx];
} else {
valid = 0;
break;
}
}
if (valid) {
maxCapital = max(maxCapital, currentCapital);
}
}
}
}
return maxCapital;
}
int main() {
char line[1000];
fgets(line, sizeof(line), stdin);
int k = atoi(line);
fgets(line, sizeof(line), stdin);
int w = atoi(line);
fgets(line, sizeof(line), stdin);
line[strcspn(line, "\n")] = '\0';
int profitsSize;
int* profits = parseArray(line, &profitsSize);
fgets(line, sizeof(line), stdin);
line[strcspn(line, "\n")] = '\0';
int capitalSize;
int* capital = parseArray(line, &capitalSize);
int result = solution(k, w, profits, capital, profitsSize);
printf("%d\n", result);
if (profits) free(profits);
if (capital) free(capital);
return 0;
}
Time & Space Complexity
Time Complexity
⏱️
n
2n
✓ Linear Growth
Space Complexity
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.