2279. Maximum Bags With Full Capacity of Rocks

Question

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

Solution

计算每个背包的剩余空间,然后进行排序。
按从小到大的顺序依次减少石头的总数。
设置i作为选取石头的计数。每次循环将i增加,直到剩余的石头数量小于0。
如果最后剩下的石头仍然大于等于0,则返回计数。
否则返回计数-1。

Code

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
class Solution {
public int maximumBags(int[] capacity, int[] rocks, int additionalRocks) {
int[] diff = new int[capacity.length];
for(int i = 0 ; i < capacity.length; i++){
diff[i] = capacity[i] - rocks[i];
}

Arrays.sort(diff);
int i = 0;
while(additionalRocks > 0 && i < diff.length){
additionalRocks -= diff[i];
i++;
}
return additionalRocks >= 0 ? i : i - 1;
}
}
Author

Xander

Posted on

2022-05-22

Updated on

2022-05-21

Licensed under

Comments