Off-by-one on range boundaries
Wrong move: Loop endpoints miss first/last candidate.
Usually fails on: Fails on minimal arrays and exact-boundary answers.
Fix: Re-derive loops from inclusive/exclusive ranges before coding.
Break down a hard problem into reliable checkpoints, edge-case handling, and complexity trade-offs.
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 ith 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.
The answer is guaranteed to fit in a 32-bit signed integer.
Example 1:
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. After finishing it you will obtain profit 1 and your capital becomes 1. With capital 1, you can either start the project indexed 1 or the project indexed 2. Since you can choose at most 2 projects, you need to finish the project indexed 2 to get the maximum capital. Therefore, output the final maximized capital, which is 0 + 1 + 3 = 4.
Example 2:
Input: k = 3, w = 0, profits = [1,2,3], capital = [0,1,2] Output: 6
Constraints:
1 <= k <= 1050 <= w <= 109n == profits.lengthn == capital.length1 <= n <= 1050 <= profits[i] <= 1040 <= capital[i] <= 109Problem summary: 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 ith 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. The answer is guaranteed to fit in a 32-bit signed integer.
Start with the most direct exhaustive search. That gives a correctness anchor before optimizing.
Pattern signal: Array · Greedy
2 0 [1,2,3] [0,1,1]
3 0 [1,2,3] [0,1,2]
maximum-subsequence-score)maximum-elegance-of-a-k-length-subsequence)Source-backed implementations are provided below for direct study and interview prep.
// Accepted solution for LeetCode #502: IPO
class Solution {
public int findMaximizedCapital(int k, int w, int[] profits, int[] capital) {
int n = capital.length;
PriorityQueue<int[]> q1 = new PriorityQueue<>((a, b) -> a[0] - b[0]);
for (int i = 0; i < n; ++i) {
q1.offer(new int[] {capital[i], profits[i]});
}
PriorityQueue<Integer> q2 = new PriorityQueue<>((a, b) -> b - a);
while (k-- > 0) {
while (!q1.isEmpty() && q1.peek()[0] <= w) {
q2.offer(q1.poll()[1]);
}
if (q2.isEmpty()) {
break;
}
w += q2.poll();
}
return w;
}
}
// Accepted solution for LeetCode #502: IPO
func findMaximizedCapital(k int, w int, profits []int, capital []int) int {
q1 := hp2{}
for i, c := range capital {
heap.Push(&q1, pair{c, profits[i]})
}
q2 := hp{}
for k > 0 {
for len(q1) > 0 && q1[0].c <= w {
heap.Push(&q2, heap.Pop(&q1).(pair).p)
}
if q2.Len() == 0 {
break
}
w += heap.Pop(&q2).(int)
k--
}
return w
}
type hp struct{ sort.IntSlice }
func (h hp) Less(i, j int) bool { return h.IntSlice[i] > h.IntSlice[j] }
func (h *hp) Push(v any) { h.IntSlice = append(h.IntSlice, v.(int)) }
func (h *hp) Pop() any {
a := h.IntSlice
v := a[len(a)-1]
h.IntSlice = a[:len(a)-1]
return v
}
type pair struct{ c, p int }
type hp2 []pair
func (h hp2) Len() int { return len(h) }
func (h hp2) Less(i, j int) bool { return h[i].c < h[j].c }
func (h hp2) Swap(i, j int) { h[i], h[j] = h[j], h[i] }
func (h *hp2) Push(v any) { *h = append(*h, v.(pair)) }
func (h *hp2) Pop() any { a := *h; v := a[len(a)-1]; *h = a[:len(a)-1]; return v }
# Accepted solution for LeetCode #502: IPO
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 w
// Accepted solution for LeetCode #502: IPO
impl Solution {
// Time O(n*log(n)) - Space O(n)
pub fn find_maximized_capital(k: i32, w: i32, profits: Vec<i32>, capital: Vec<i32>) -> i32 {
use std::collections::BinaryHeap;
let mut sorted_jobs: Vec<(i32, i32)> = (0..profits.len())
.map(|i| (capital[i], profits[i]))
.collect();
sorted_jobs.sort();
sorted_jobs.reverse();
let mut heap = BinaryHeap::<i32>::new();
// The current capital.
let mut cap = w;
for _ in 0..k {
while sorted_jobs.len() > 0 && sorted_jobs[sorted_jobs.len() - 1].0 <= cap {
match sorted_jobs.pop() {
Some((_, p)) => heap.push(p),
None => unreachable!(),
}
}
match heap.pop() {
Some(v) => cap += v,
None => break,
}
}
cap
}
}
// Accepted solution for LeetCode #502: IPO
function findMaximizedCapital(
k: number,
w: number,
profits: number[],
capital: number[],
): number {
const minCapital = new PriorityQueue({ compare: (a, b) => a[1] - b[1] });
const maxProfit = new MaxPriorityQueue();
for (let i = 0; i < profits.length; i++) {
minCapital.enqueue([profits[i], capital[i]]);
}
let profit = w;
for (let i = 0; i < k; i++) {
while (!minCapital.isEmpty() && minCapital.front()[1] <= profit) {
const element = minCapital.dequeue();
maxProfit.enqueue(element[0]);
}
if (maxProfit.isEmpty()) break;
const { element } = maxProfit.dequeue();
profit += element;
}
return profit;
}
Use this to step through a reusable interview workflow for this problem.
Try every possible combination of choices. With n items each having two states (include/exclude), the search space is 2ⁿ. Evaluating each combination takes O(n), giving O(n × 2ⁿ). The recursion stack or subset storage uses O(n) space.
Greedy algorithms typically sort the input (O(n log n)) then make a single pass (O(n)). The sort dominates. If the input is already sorted or the greedy choice can be computed without sorting, time drops to O(n). Proving greedy correctness (exchange argument) is harder than the implementation.
Review these before coding to avoid predictable interview regressions.
Wrong move: Loop endpoints miss first/last candidate.
Usually fails on: Fails on minimal arrays and exact-boundary answers.
Fix: Re-derive loops from inclusive/exclusive ranges before coding.
Wrong move: Locally optimal choices may fail globally.
Usually fails on: Counterexamples appear on crafted input orderings.
Fix: Verify with exchange argument or monotonic objective before committing.