#3814

Maximum Capacity Within Budget

Medium
ArrayTwo PointersBinary SearchSortingTwo PointersSorting
LeetCode ↗

Approaches

Brute ForceOptimal
Complexity Comparison
Brute ForceOptimal 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
  1. 1Step 1: Pair costs with capacities and sort them by costs.
  2. 2Step 2: Create a prefix array to store the maximum capacity up to each index.
  3. 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.