#3814
Maximum Capacity Within Budget
MediumArrayTwo PointersBinary SearchSortingTwo PointersSorting
Approaches
Brute ForceOptimal
Complexity Comparison
| Brute Force | Optimal Solution★ | |
|---|---|---|
| Time | O(n²) | O(n log n) |
| Space | O(1) | O(n) |
💡
Intuition
Time O(n log n)Space O(n)
Sort machines by cost and use a two-pointer technique to find the best combination of machines within budget efficiently.
⚙️
Algorithm
3 steps- 1Step 1: Pair costs with capacities and sort them by costs.
- 2Step 2: Create a prefix array to store the maximum capacity up to each index.
- 3Step 3: Use two pointers to find the best pair of machines that fit within the budget.
solution.py15 lines
1def maxCapacity(costs, capacity, budget):
2 machines = sorted(zip(costs, capacity))
3 n = len(machines)
4 prefMax = [0] * n
5 prefMax[0] = machines[0][1]
6 for i in range(1, n):
7 prefMax[i] = max(prefMax[i-1], machines[i][1])
8 max_capacity = 0
9 for i in range(n):
10 j = n - 1
11 while j > i and machines[i][0] + machines[j][0] >= budget:
12 j -= 1
13 if j > i:
14 max_capacity = max(max_capacity, machines[i][1] + prefMax[j])
15 return max_capacityℹ
Complexity note: Sorting the machines takes O(n log n), and the two-pointer search is O(n).
- 1Sorting helps to efficiently pair machines within budget.
- 2Using a prefix max array allows quick access to the best capacity.
Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.