LeetCode #1231. Divide Chocolate

题目描述:

You have one chocolate bar that consists of some chunks. Each chunk has its own sweetness given by the array sweetness.

You want to share the chocolate with your K friends so you start cutting the chocolate bar into K+1 pieces using K cuts, each piece consists of some consecutive chunks.

Being generous, you will eat the piece with the minimum total sweetness and give the other pieces to your friends.

Find the maximum total sweetness of the piece you can get by cutting the chocolate bar optimally.

Example 1:

Input: sweetness = [1,2,3,4,5,6,7,8,9], K = 5
Output: 6
Explanation: You can divide the chocolate to [1,2,3], [4,5], [6], [7], [8], [9]

Example 2:

Input: sweetness = [5,6,7,8,9,1,2,3,4], K = 8
Output: 1
Explanation: There is only one way to cut the bar into 9 pieces.

Example 3:

Input: sweetness = [1,2,2,1,2,2,1,2,2], K = 2
Output: 5
Explanation: You can divide the chocolate to [1,2,2], [1,2,2], [1,2,2]

Constraints:

  • 0 <= K < sweetness.length <= 10^4
  • 1 <= sweetness[i] <= 10^5
class Solution {
public:
    int maximizeSweetness(vector<int>& sweetness, int K) {
        int begin=sweetness[0];
        int end=0;
        for(int x:sweetness)
        {
            begin=min(begin,x);
            end+=x;
        }
        while(begin<end)
        {
            int mid=(begin+end)/2;
            if(begin==mid) // mid可能等于begin,为避免无限循环,需要额外判断
            {
                if(count_chunks(sweetness,end)>=K+1) return end;
                else return begin;
            }
            // 当所有块甜度都大于等于mid时,得到的最多块数
            int count=count_chunks(sweetness,mid);
            if(count<K+1) end=mid-1; // 当最大的块数都小于K+1时,说明mid过大
            else begin=mid;
        }
        return begin;
    }
    
    int count_chunks(vector<int>& v, int min_sweetness)
    {
        int i=0;
        int count=0;
        int sum=0;
        while(i<v.size())
        {
            sum+=v[i];
            if(sum>=min_sweetness)
            {
                sum=0;
                count++;
            }
            i++;
        } // 注意是所有块甜度都要大于等于最小值,那么最后剩余的部分不能算上
        return count;
    }
};

 

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值