2279. Maximum Bags With Full Capacity of Rocks Medium
1/**
2 * [2279] Maximum Bags With Full Capacity of Rocks
3 *
4 * You have n bags numbered from 0 to n - 1. You are given two 0-indexed integer arrays capacity and rocks. The i^th bag can hold a maximum of capacity[i] rocks and currently contains rocks[i] rocks. You are also given an integer additionalRocks, the number of additional rocks you can place in any of the bags.
5 * Return the maximum number of bags that could have full capacity after placing the additional rocks in some bags.
6 *
7 * Example 1:
8 *
9 * Input: capacity = [2,3,4,5], rocks = [1,2,4,4], additionalRocks = 2
10 * Output: 3
11 * Explanation:
12 * Place 1 rock in bag 0 and 1 rock in bag 1.
13 * The number of rocks in each bag are now [2,3,4,4].
14 * Bags 0, 1, and 2 have full capacity.
15 * There are 3 bags at full capacity, so we return 3.
16 * It can be shown that it is not possible to have more than 3 bags at full capacity.
17 * Note that there may be other ways of placing the rocks that result in an answer of 3.
18 *
19 * Example 2:
20 *
21 * Input: capacity = [10,2,2], rocks = [2,2,0], additionalRocks = 100
22 * Output: 3
23 * Explanation:
24 * Place 8 rocks in bag 0 and 2 rocks in bag 2.
25 * The number of rocks in each bag are now [10,2,2].
26 * Bags 0, 1, and 2 have full capacity.
27 * There are 3 bags at full capacity, so we return 3.
28 * It can be shown that it is not possible to have more than 3 bags at full capacity.
29 * Note that we did not use all of the additional rocks.
30 *
31 *
32 * Constraints:
33 *
34 * n == capacity.length == rocks.length
35 * 1 <= n <= 5 * 10^4
36 * 1 <= capacity[i] <= 10^9
37 * 0 <= rocks[i] <= capacity[i]
38 * 1 <= additionalRocks <= 10^9
39 *
40 */
41pub struct Solution {}
42
43// problem: https://leetcode.com/problems/maximum-bags-with-full-capacity-of-rocks/
44// discuss: https://leetcode.com/problems/maximum-bags-with-full-capacity-of-rocks/discuss/?currentPage=1&orderBy=most_votes&query=
45
46// submission codes start here
47
48impl Solution {
49 pub fn maximum_bags(capacity: Vec<i32>, rocks: Vec<i32>, additional_rocks: i32) -> i32 {
50 let mut space = vec![0; capacity.len()];
51 for i in 0..capacity.len() {
52 space[i] = capacity[i] - rocks[i];
53 }
54
55 space.sort();
56
57 let mut result = 0;
58 let mut remaining_additional_rocks = additional_rocks;
59
60 for i in 0..space.len() {
61 remaining_additional_rocks -= space[i];
62 if remaining_additional_rocks >= 0 {
63 result += 1;
64 } else {
65 break;
66 }
67 }
68 result
69 }
70}
71
72// submission codes end
73
74#[cfg(test)]
75mod tests {
76 use super::*;
77
78 #[test]
79 fn test_2279() {
80 assert_eq!(
81 Solution::maximum_bags(vec![10, 2, 2], vec![2, 2, 0], 100),
82 3
83 );
84 }
85}
86
Back
© 2025 bowen.ge All Rights Reserved.