题目描述:
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;
}
};