2226. Maximum Candies Allocated to K Children

        //题目和砍木头和875 koko吃香蕉一样
        //画图画图画图 重要的事情说三遍
        //             max NO. candies/pile  
        //candies    1  2  3  4  5  6  7  8
        
        //   5            5  2  1  1  1  0  0  0
        //   8            8  4  2  2  1  1  1  1
        //   6            6  3  2  1  1  1  0  0
        
    //Tot Candies  19  9  5  4  3  2  1  1
        
        // 1. 二分法来处理这个问题, 以 每个篮子里多少个糖果 来二分。
        //     因为通过max No. candies/pile 可以计算出可以分出来多少篮子糖果。
        //2. 二分的时候把 通过Mid计算出来的篮子数目 和 K个小朋友来对比
        //     如果比K大,说明份的分数太多了。增加每个篮子里的糖果数目
        //     如果比K小,说明分的分数太少。减少每个篮子里的糖果数目
        // 3. 退出的时候,因为题目要求maximum number of candies each child can get
        //      说明尽量每个篮子分的糖果多一些
        //      比如假设每个篮子分7,8 个糖果分出来的篮子糖果一样,并且K也是1。那就得每个篮子分8个。、

class Solution {
public:
    long long calcNumPiles(int numCandiesPerPile, vector<int>& candies){
        long long ret = 0;
        
        for(int candy: candies)
            ret += candy / numCandiesPerPile;
        
        return ret;
    }
    
    int maximumCandies(vector<int>& candies, long long k) {

        
        int start = 1;
        int maxCandiesPerPile = 0;
        
        for(int candy: candies){
            if(candy > maxCandiesPerPile)
                maxCandiesPerPile = candy;
        }
        
        int end = maxCandiesPerPile;
        
        while(start + 1 < end) {
            int mid = start + (end - start) / 2;
            
            long long numPiles = calcNumPiles(mid, candies);
            
            if(numPiles >= k)
                start = mid;
            else
                end = mid;
        }
        
        if(calcNumPiles(end, candies) >= k)
            return end;
        if(calcNumPiles(start, candies) >= k)
            return start;
        
        return 0;
    }
};

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值