Maximum Capacity Within Budget solution and explanation
4 more videos on this problem
Maximum Capacity Within Budget 🔥 LeetCode 3814 | Weekly Contest 485 | Greedy + Sorting Study Placement · 20:54 · 2K views
Maximum Capacity Within Budget | Leetcode 3814 | Weekly Contest 485 | Java Code | Developer CoderDeveloper Coder · 20:50 · 1K views
Leetcode 3814 | Maximum Capacity Within BudgetCodeWithMeGuys · 11:15 · 715 views
3814. Maximum Capacity Within Budget (Leetcode Medium)Programming Live with Larry · 13:02 · 550 views
LeetCode 3814 | Maximum Capacity Within Budget | Optimal Binary Search ApproachCode Kage · 18:16 · 231 views
The problem
You are given two integer arrays costs and capacity, both of length n, where costs[i] represents the purchase cost of the ith machine and capacity[i] represents its performance capacity.
You are also given an integer budget.
You may select at most two distinct machines such that the total cost of the selected machines is strictly less than budget.
Return the maximum achievable total capacity of the selected machines.
Example 1:
Input: costs = [4,8,5,3], capacity = [1,5,2,7], budget = 8
Output: 8
Explanation:
- Choose two machines with
costs[0] = 4andcosts[3] = 3. - The total cost is
4 + 3 = 7, which is strictly less thanbudget = 8. - The maximum total capacity is
capacity[0] + capacity[3] = 1 + 7 = 8.
Example 2:
Input: costs = [3,5,7,4], capacity = [2,4,3,6], budget = 7
Output: 6
Explanation:
- Choose one machine with
costs[3] = 4. - The total cost is 4, which is strictly less than
budget = 7. - The maximum total capacity is
capacity[3] = 6.
Example 3:
Input: costs = [2,2,2], capacity = [3,5,4], budget = 5
Output: 9
Explanation:
- Choose two machines with
costs[1] = 2andcosts[2] = 2. - The total cost is
2 + 2 = 4, which is strictly less thanbudget = 5. - The maximum total capacity is
capacity[1] + capacity[2] = 5 + 4 = 9.
Constraints:
1 <= n == costs.length == capacity.length <= 1051 <= costs[i], capacity[i] <= 1051 <= budget <= 2 * 105
Approach overview
Problem Overview: You are given arrays describing capacity and cost, along with a total budget. The goal is to select valid elements such that the total cost stays within the budget while maximizing the achievable capacity. The challenge is balancing cost constraints with capacity maximization efficiently.
Approach 1: Brute Force Pair/Subset Check (O(n^2) time, O(1) space)
The most direct approach is to iterate through all valid combinations and compute their total cost and resulting capacity. For each candidate pair or combination, check whether the cost is within the budget and track the maximum capacity found. This uses simple Array iteration with nested loops. The approach is easy to implement but quickly becomes impractical as n grows because every pair (or candidate combination) must be evaluated.
Approach 2: Sorting + Two Pointers (O(n log n) time, O(1) space)
Sort the items by cost first. After sorting, use the two pointers technique to scan from both ends while maintaining the budget constraint. If the combined cost exceeds the budget, move the higher-cost pointer inward; otherwise compute the resulting capacity and update the answer. Sorting reduces the search space and allows efficient pruning during the scan. This technique is common in problems involving pair constraints and works well when decisions depend on ordered cost values. See more patterns in two pointers problems.
Approach 3: Sorting + Ordered Set (O(n log n) time, O(n) space)
Sort the elements by cost so that cheaper options are processed first. Maintain an ordered set (such as TreeSet, bisect-backed structure, or balanced BST) storing candidate capacities encountered so far. For each element, compute the remaining budget and use binary search on the ordered structure to find the best compatible candidate. This allows efficient lookup of the optimal capacity that fits within the remaining cost constraint. Each insertion and query takes O(log n), giving an overall O(n log n) solution. This approach combines sorting with binary search style lookups to avoid checking all pairs.
Recommended for interviews: Interviewers expect the optimized Sorting + Ordered Set or a similar O(n log n) strategy. Brute force demonstrates baseline reasoning but fails scalability constraints. Using sorting with efficient lookups shows you understand how to combine ordered data structures with binary search to prune the search space effectively.
Solution
We first filter out all machines with costs less than the budget and sort them by cost in ascending order, recording them in the array arr, where arr[i] = (costs[i], capacity[i]). If arr is empty, we cannot buy any machine, so we return 0.
Otherwise, we can obtain the machine with the maximum capacity in arr and initialize the answer with this capacity.
Next, we use a two-pointer approach to iterate through pairs of machines in arr, using an ordered set remain to maintain the capacities of all currently available machines. Initially, remain contains the capacities of all machines in arr.
We use pointers i and j pointing to the beginning and end of arr, respectively. For each i, we remove arr[i] from remain, and then move pointer j until arr[i].cost + arr[j].cost < budget. During this process, we remove the machines that do not satisfy the condition from remain. At this point, any machine in remain can be bought together with arr[i]. We take the machine with the maximum capacity from remain, add its capacity to arr[i]'s capacity, and update the answer. Finally, we return the answer.
The time complexity is O(n log n), and the space complexity is O(n), where n is the number of machines.
class Solution:
def maxCapacity(self, costs: List[int], capacity: List[int], budget: int) -> int:
arr = []
for a, b in zip(costs, capacity):
if a < budget:
arr.append((a, b))
if not arr:
return 0
arr.sort()
remain = SortedList()
for i, (_, b) in enumerate(arr):
remain.add((b, i))
i, j = 0, len(arr) - 1
ans = remain[-1][0]
while i < j:
remain.discard((arr[i][1], i))
while i < j and arr[i][0] + arr[j][0] >= budget:
remain.discard((arr[j][1], j))
j -= 1
if remain:
ans = max(ans, arr[i][1] + remain[-1][0])
i += 1
return ansclass Solution {
public int maxCapacity(int[] costs, int[] capacity, int budget) {
List<int[]> arr = new ArrayList<>();
for (int k = 0; k < costs.length; k++) {
int a = costs[k], b = capacity[k];
if (a < budget) {
arr.add(new int[] {a, b});
}
}
if (arr.isEmpty()) {
return 0;
}
arr.sort(Comparator.comparingInt(o -> o[0]));
TreeSet<int[]> remain = new TreeSet<>((x, y) -> {
if (x[0] != y[0]) {
return x[0] - y[0];
}
return x[1] - y[1];
});
for (int i = 0; i < arr.size(); i++) {
remain.add(new int[] {arr.get(i)[1], i});
}
int i = 0, j = arr.size() - 1;
int ans = remain.last()[0];
while (i < j) {
remain.remove(new int[] {arr.get(i)[1], i});
while (i < j && arr.get(i)[0] + arr.get(j)[0] >= budget) {
remain.remove(new int[] {arr.get(j)[1], j});
j--;
}
if (!remain.isEmpty()) {
ans = Math.max(ans, arr.get(i)[1] + remain.last()[0]);
}
i++;
}
return ans;
}
}class Solution {
public:
int maxCapacity(vector<int>& costs, vector<int>& capacity, int budget) {
vector<pair<int, int>> arr;
for (int k = 0; k < costs.size(); k++) {
int a = costs[k], b = capacity[k];
if (a < budget) {
arr.emplace_back(a, b);
}
}
if (arr.empty()) {
return 0;
}
sort(arr.begin(), arr.end());
multiset<pair<int, int>> remain;
for (int i = 0; i < arr.size(); i++) {
remain.insert({arr[i].second, i});
}
int i = 0, j = arr.size() - 1;
int ans = prev(remain.end())->first;
while (i < j) {
remain.erase(remain.find({arr[i].second, i}));
while (i < j && arr[i].first + arr[j].first >= budget) {
remain.erase(remain.find({arr[j].second, j}));
j--;
}
if (!remain.empty()) {
ans = max(ans, arr[i].second + prev(remain.end())->first);
}
i++;
}
return ans;
}
};type Node struct {
b int
i int
}
type MaxHeap []Node
func (h MaxHeap) Len() int { return len(h) }
func (h MaxHeap) Less(i, j int) bool {
if h[i].b != h[j].b {
return h[i].b > h[j].b
}
return h[i].i > h[j].i
}
func (h MaxHeap) Swap(i, j int) { h[i], h[j] = h[j], h[i] }
func (h *MaxHeap) Push(x interface{}) {
*h = append(*h, x.(Node))
}
func (h *MaxHeap) Pop() interface{} {
old := *h
n := len(old)
x := old[n-1]
*h = old[:n-1]
return x
}
func maxCapacity(costs []int, capacity []int, budget int) int {
arr := make([][2]int, 0)
for k := 0; k < len(costs); k++ {
a, b := costs[k], capacity[k]
if a < budget {
arr = append(arr, [2]int{a, b})
}
}
if len(arr) == 0 {
return 0
}
sort.Slice(arr, func(i, j int) bool {
if arr[i][0] != arr[j][0] {
return arr[i][0] < arr[j][0]
}
return arr[i][1] < arr[j][1]
})
alive := make([]bool, len(arr))
h := &MaxHeap{}
for i := 0; i < len(arr); i++ {
alive[i] = true
heap.Push(h, Node{arr[i][1], i})
}
i, j := 0, len(arr)-1
for h.Len() > 0 && !alive[(*h)[0].i] {
heap.Pop(h)
}
ans := (*h)[0].b
for i < j {
alive[i] = false
for i < j && arr[i][0]+arr[j][0] >= budget {
alive[j] = false
j--
}
for h.Len() > 0 && !alive[(*h)[0].i] {
heap.Pop(h)
}
if h.Len() > 0 {
if arr[i][1]+(*h)[0].b > ans {
ans = arr[i][1] + (*h)[0].b
}
}
i++
}
return ans
}Complexity analysis
| Approach | Time | Space | When to Use |
|---|---|---|---|
| Brute Force Enumeration | O(n^2) | O(1) | Small inputs or verifying correctness during prototyping |
| Sorting + Two Pointers | O(n log n) | O(1) | When evaluating pair combinations under a cost constraint |
| Sorting + Ordered Set | O(n log n) | O(n) | General scalable solution requiring fast lookups for best compatible candidate |
Frequently asked questions
Is Maximum Capacity Within Budget easy or hard?
Maximum Capacity Within Budget is generally considered a Medium difficulty problem. The brute-force idea is straightforward, but reaching the optimal O(n log n) solution requires recognizing the need for sorting and binary-search-based lookups.
Maximum Capacity Within Budget Python/Java solution
Implement the optimized strategy by sorting items by cost and maintaining a sorted structure for candidate capacities. In Python, this can be done with a list and bisect operations or a library-backed sorted container. Java implementations often use TreeSet, while C++ commonly uses multiset.
How to solve Maximum Capacity Within Budget in O(n log n)?
Sort the elements by cost, then iterate through them while maintaining an ordered structure of candidate capacities. For each element, compute the remaining budget and perform a binary search to locate the best compatible candidate. This avoids checking every pair explicitly and keeps the total runtime at O(n log n).
What is the best approach for Maximum Capacity Within Budget?
The most practical approach uses sorting combined with an ordered set or balanced tree. After sorting by cost, you iterate through items and use binary search on previously processed candidates to find the best capacity that still fits within the remaining budget. This reduces the search from O(n^2) to O(n log n).
Is Maximum Capacity Within Budget asked at Google/Amazon/Meta?
Problems combining budget constraints, sorting, and binary search appear frequently in interviews at companies like Amazon, Google, and Meta. Variants of this problem test the ability to combine arrays, ordered data structures, and efficient lookups to reduce brute-force search.
What data structure is used in Maximum Capacity Within Budget?
The optimized approach typically uses an ordered set or balanced binary search tree. Structures like TreeSet (Java), multiset (C++), or a sorted list with binary search in Python allow efficient O(log n) insertions and lookups.
What is the time complexity of Maximum Capacity Within Budget?
The optimal solution runs in O(n log n) time due to sorting and ordered set operations. Each insertion and lookup in the ordered structure costs O(log n), and this happens once per element. Space complexity is typically O(n) for storing candidates.
