[LeetCode] Maximum Capacity Within Budget

3814. Maximum Capacity Within Budget

You are given two integer arrays costs and capacity, both of length n, where costs[i] represents the purchase cost of the i^th 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.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
class Solution {
public:
int maxCapacity(vector<int>& costs, vector<int>& capacity, int budget) {
--budget;
deque<pair<int,int>> dq;
vector<pair<int,int>> S;
for(int i = 0; i < costs.size(); i++) S.push_back({costs[i], capacity[i]});
sort(begin(S), end(S));
int res = 0;
while(S.size()) {
auto [c,cap] = S.back(); S.pop_back();
if(c > budget) continue;
if(dq.size() and dq[0].first + c <= budget) {
auto it = prev(lower_bound(begin(dq), end(dq), pair<int,int>{budget - c + 1, -1}));
res = max(res, cap + it->second);
} else res = max(res, cap);
while(dq.size() and dq[0].second <= cap) dq.pop_front();
dq.push_front({c,cap});
}
return res;
}
};
Author: Song Hayoung
Link: https://songhayoung.github.io/2026/09/04/PS/LeetCode/maximum-capacity-within-budget/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.