[LeetCode] Divide Chocolate

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.

  • Time : O(nlogn)
  • Space : O(1)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
class Solution {
public:
int maximizeSweetness(vector<int>& sweetness, int k) {
int l = 0, r = INT_MAX, res = 0;
while(l <= r) {
int m = l + (r-l)/2, mi = INT_MAX, sum = 0, cnt = 0;

for(auto sweet: sweetness) {
sum += sweet;
if(sum >= m) {
mi = min(mi, sum);
sum = 0;
cnt++;
}
}

if(cnt >= k + 1) res = max(res, mi);
if(cnt < k + 1) r = m - 1;
else l = m + 1;
}
return res;
}
};
Author: Song Hayoung
Link: https://songhayoung.github.io/2022/02/15/PS/LeetCode/divide-chocolate/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.