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.
Move from brute-force thinking to an efficient approach using array strategy.
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:
costs[0] = 4 and costs[3] = 3.4 + 3 = 7, which is strictly less than budget = 8.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:
costs[3] = 4.budget = 7.capacity[3] = 6.Example 3:
Input: costs = [2,2,2], capacity = [3,5,4], budget = 5
Output: 9
Explanation:
costs[1] = 2 and costs[2] = 2.2 + 2 = 4, which is strictly less than budget = 5.capacity[1] + capacity[2] = 5 + 4 = 9.Constraints:
1 <= n == costs.length == capacity.length <= 1051 <= costs[i], capacity[i] <= 1051 <= budget <= 2 * 105Problem summary: 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.
Start with the most direct exhaustive search. That gives a correctness anchor before optimizing.
Pattern signal: Array · Two Pointers · Binary Search
[4,8,5,3] [1,5,2,7] 8
[3,5,7,4] [2,4,3,6] 7
[2,2,2] [3,5,4] 5
Source-backed implementations are provided below for direct study and interview prep.
// Accepted solution for LeetCode #3814: Maximum Capacity Within Budget
class 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;
}
}
// Accepted solution for LeetCode #3814: Maximum Capacity Within Budget
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
}
# Accepted solution for LeetCode #3814: Maximum Capacity Within Budget
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 ans
// Accepted solution for LeetCode #3814: Maximum Capacity Within Budget
// Rust example auto-generated from java reference.
// Replace the signature and local types with the exact LeetCode harness for this problem.
impl Solution {
pub fn rust_example() {
// Port the logic from the reference block below.
}
}
// Reference (java):
// // Accepted solution for LeetCode #3814: Maximum Capacity Within Budget
// class 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;
// }
// }
// Accepted solution for LeetCode #3814: Maximum Capacity Within Budget
// Auto-generated TypeScript example from java.
function exampleSolution(): void {
}
// Reference (java):
// // Accepted solution for LeetCode #3814: Maximum Capacity Within Budget
// class 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;
// }
// }
Use this to step through a reusable interview workflow for this problem.
Two nested loops check every pair of elements. The outer loop picks one element, the inner loop scans the rest. For n elements that is n × (n−1)/2 comparisons = O(n²). No extra memory — just two loop variables.
Each pointer traverses the array at most once. With two pointers moving inward (or both moving right), the total number of steps is bounded by n. Each comparison is O(1), giving O(n) overall. No auxiliary data structures are needed — just two index variables.
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: Advancing both pointers shrinks the search space too aggressively and skips candidates.
Usually fails on: A valid pair can be skipped when only one side should move.
Fix: Move exactly one pointer per decision branch based on invariant.
Wrong move: Setting `lo = mid` or `hi = mid` can stall and create an infinite loop.
Usually fails on: Two-element ranges never converge.
Fix: Use `lo = mid + 1` or `hi = mid - 1` where appropriate.