3814. Maximum Capacity Within Budget Medium

@problem@discussion
#Array#Two Pointers#Binary Search#Sorting



1/**
2 * [3814] Maximum Capacity Within Budget
3 *
4 * 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.
5 * You are also given an integer budget.
6 * You may select at most two distinct machines such that the total cost of the selected machines is strictly less than budget.
7 * Return the maximum achievable total capacity of the selected machines.
8 *  
9 * <strong class="example">Example 1:
10 * <div class="example-block">
11 * Input: <span class="example-io">costs = [4,8,5,3], capacity = [1,5,2,7], budget = 8</span>
12 * Output: <span class="example-io">8</span>
13 * Explanation:
14 * 
15 * 	Choose two machines with costs[0] = 4 and costs[3] = 3.
16 * 	The total cost is 4 + 3 = 7, which is strictly less than budget = 8.
17 * 	The maximum total capacity is capacity[0] + capacity[3] = 1 + 7 = 8.
18 * </div>
19 * <strong class="example">Example 2:
20 * <div class="example-block">
21 * Input: <span class="example-io">costs = [3,5,7,4], capacity = [2,4,3,6], budget = 7</span>
22 * Output: <span class="example-io">6</span>
23 * Explanation:
24 * 
25 * 	Choose one machine with costs[3] = 4.
26 * 	The total cost is 4, which is strictly less than budget = 7.
27 * 	The maximum total capacity is capacity[3] = 6.
28 * </div>
29 * <strong class="example">Example 3:
30 * <div class="example-block">
31 * Input: <span class="example-io">costs = [2,2,2], capacity = [3,5,4], budget = 5</span>
32 * Output: <span class="example-io">9</span>
33 * Explanation:
34 * 
35 * 	Choose two machines with costs[1] = 2 and costs[2] = 2.
36 * 	The total cost is 2 + 2 = 4, which is strictly less than budget = 5.
37 * 	The maximum total capacity is capacity[1] + capacity[2] = 5 + 4 = 9.
38 * </div>
39 *  
40 * Constraints:
41 * 
42 * 	1 <= n == costs.length == capacity.length <= 10^5
43 * 	1 <= costs[i], capacity[i] <= 10^5
44 * 	1 <= budget <= 2 * 10^5
45 * 
46 */
47pub struct Solution {}
48
49// problem: https://leetcode.com/problems/maximum-capacity-within-budget/
50// discuss: https://leetcode.com/problems/maximum-capacity-within-budget/discuss/?currentPage=1&orderBy=most_votes&query=
51
52// submission codes start here
53
54impl Solution {
55    pub fn max_capacity(costs: Vec<i32>, capacity: Vec<i32>, budget: i32) -> i32 {
56        0
57    }
58}
59
60// submission codes end
61
62#[cfg(test)]
63mod tests {
64    use super::*;
65
66    #[test]
67    fn test_3814() {
68    }
69}
70

Back
© 2026 bowen.ge All Rights Reserved.