leetcode 1231.Divide Chocolate (数组分段和最小值的最大值)

利用二分查找解决LeetCode 1231题,最大化保留甜度最低的巧克力块,确保分享给K个朋友后,自身获得最大甜度。

比较简单,就不翻译了
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

一开始想了半天,搞了个O(n^2*k) DP,理所当然的TLE。苦思冥想之下打开百度作弊 查找资料,发现了分段和最大值最小问题,然后发现自己是个傻逼 大概是二分查找极不熟悉的后果。

class Solution {
public:
    int divis(vector<int>& s,int sum){//满足最小分段和为sum情况下的分段上限
        int now=0,r=0;
        for(int i=0;i<s.size();++i){
            now+=s[i];
            if(now>=sum){
                ++r;
                now=0;
            }
        }
        return r;
    }
    int maximizeSweetness(vector<int>& s, int k) {
        int t=(1<<30),r=0;
        while(t>0){
            if(divis(s,r+t)>k) r+=t;
            t>>=1;
        }
        return r;
    }
};

Time O(nlog(sum(s)))
Memory O(1) (extra)

评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值