[M数学] lc2171. 拿出最少数目的魔法豆(数学+前缀和)

文章介绍了在LeetCode问题中如何通过排序和前缀和计算找到最少移除魔法豆的数量,以使数组中所有元素相等。解决方案涉及排序数组、计算代价并更新最小结果。
摘要由CSDN通过智能技术生成

1. 题目来源

链接:2171. 拿出最少数目的魔法豆

2. 题目解析

比较简单直接的思路吧,会发现最终的转换成的数组,每个元素要么是 0,不参与结果判断,要么大家都一样。想一想这个都一样的数据有什么特殊性质。

简单想想就懂,这个都一样的数据,一定是数组中的某个元素,因为如果不是某个元素的话,其他的元素向它靠拢,肯定花费其他更多的代价。至于证明,看官解即可。

解决方案:

  • 排序,求前缀和
  • 依次计算当前元素成为这个一样元素的代价是多少
  • 代价=左侧元素的总和+右侧各个元素与当前元素的差值总和
  • 前缀和处理即可

注意下,中间计算过程会爆 int,注意转 long long 即可

还有就是官解的解答很巧妙,思路都一样,可以借鉴下。


  • 时间复杂度 O ( n ) O(n) O(n)
  • 空间复杂度 O ( 1 ) O(1) O(1)

class Solution {
public:
    long long minimumRemoval(vector<int>& beans) {
        typedef long long LL;
        sort(beans.begin(), beans.end());
        LL res = 1e18;
        int n = beans.size();
        vector<int> s(n + 1, 0);
        vector<LL> beSum(n + 1);
        for (int i = 1; i <= n; i ++ ) beSum[i] += 0ll + beSum[i - 1] + beans[i - 1]; 
        for (int i = 1; i <= n; i ++ ) {
            LL cnt = 0ll + beSum[i - 1] + beSum[n] - beSum[i] - 1ll * (n - i) * beans[i - 1];
            if (res > cnt) {
                res = cnt;
            }
        }

        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 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;
    }
};
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Ypuyu

如果帮助到你,可以请作者喝水~

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值