[LeetCode] Maximum Bags With Full Capacity of Rocks

2279. Maximum Bags With Full Capacity of Rocks

You have n bags numbered from 0 to n - 1. You are given two 0-indexed integer arrays capacity and rocks. The ith 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.

Return the maximum number of bags that could have full capacity after placing the additional rocks in some bags.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
class Solution {
public:
int maximumBags(vector<int>& capacity, vector<int>& rocks, int additionalRocks) {
int n = capacity.size();
vector<int> remain(n);
for(int i = 0; i < n; i++) {
remain[i] = capacity[i] - rocks[i];
}
sort(begin(remain), end(remain));
int res = 0, i = 0;
while(i < n and additionalRocks) {
if(remain[i] == 0) res++;
else if(remain[i] <= additionalRocks) {
additionalRocks -= remain[i]; res++;
} else break;
i++;
}
return res;
}
};
Author: Song Hayoung
Link: https://songhayoung.github.io/2022/05/22/PS/LeetCode/maximum-bags-with-full-capacity-of-rocks/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.