系列文章目录
拿出最少数目的魔法豆
题目
给定一个正整数数组 beans ,其中每个整数表示一个袋子里装的魔法豆的数目。
请你从每个袋子中拿出一些豆子(也可以不拿出),使得剩下的非空袋子中(即至少还有一颗魔法豆的袋子)魔法豆的数目相等。一旦把魔法豆从袋子中取出,你不能再将它放到任何袋子中。
请返回你需要拿出魔法豆最少数目。
官方题解
官方代码
代码如下(示例):
class Solution {
public:
long long minimumRemoval(vector<int>& beans) {
int n = beans.size();
sort(beans.begin(), beans.end());
long long total = accumulate(beans.begin(), beans.end(), 0LL); // 豆子总数
long long res = total; // 最少需要移除的豆子数
for (int i = 0; i < n; i++) {
res = min(res, total - (long long)beans[i] * (n - i));
}
return res;
}
};
作者:力扣官方题解
链接:https://leetcode.cn/problems/removing-minimum-number-of-magic-beans/solutions/1270306/na-chu-zui-shao-shu-mu-de-mo-fa-dou-by-l-dhsl/
来源:力扣(LeetCode)
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。
解题代码
代码如下(示例):
class Solution {
public:
long long minimumRemoval(vector<int>& beans) {
int n=beans.size();
sort(beans.begin(),beans.end());
long long s=0;
for(int i=0;i<n;i++)
s+=beans[i];
long long left=0;
for(int i=0;i<n;i++){
left=max(left,beans[i]*1ll*(n-i));
}
return s-left;
}
};
总结
以上为我的题解