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.
We want to maximize the minimum sweetness among all pieces after making K cuts. If we try a candidate minimum sweetness, we can check if it’s possible to split the chocolate into at least K+1 pieces, each with at least that much sweetness. If yes, we can try a higher value; if not, we try lower. This is a classic binary search on the answer.
classSolution {
public:int maximizeSweetness(vector<int>& s, int k) {
int l =1, r = accumulate(s.begin(), s.end(), 0) / (k+1), ans =0;
while (l <= r) {
int m = l + (r-l)/2, cnt =0, sum =0;
for (int x : s) {
sum += x;
if (sum >= m) {
cnt++;
sum =0;
}
}
if (cnt >= k+1) ans = m, l = m+1;
else r = m-1;
}
return ans;
}
};
classSolution {
publicintmaximizeSweetness(int[] s, int k) {
int l = 1, r = 0, ans = 0;
for (int v : s) r += v;
r /= (k+1);
while (l <= r) {
int m = l + (r-l)/2, cnt = 0, sum = 0;
for (int x : s) {
sum += x;
if (sum >= m) {
cnt++;
sum = 0;
}
}
if (cnt >= k+1) {
ans = m;
l = m+1;
} else {
r = m-1;
}
}
return ans;
}
}
classSolution {
funmaximizeSweetness(s: IntArray, k: Int): Int {
var l = 1var r = s.sum() / (k+1)
var ans = 0while (l <= r) {
val m = l + (r-l)/2var cnt = 0var sum = 0for (x in s) {
sum += x
if (sum >= m) {
cnt++ sum = 0 }
}
if (cnt >= k+1) {
ans = m
l = m+1 } else {
r = m-1 }
}
return ans
}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
classSolution:
defmaximizeSweetness(self, s: list[int], k: int) -> int:
l, r =1, sum(s) // (k+1)
ans =0while l <= r:
m = (l + r) //2 cnt, sm =0, 0for x in s:
sm += x
if sm >= m:
cnt +=1 sm =0if cnt >= k+1:
ans = m
l = m+1else:
r = m-1return ans
impl Solution {
pubfnmaximize_sweetness(s: Vec<i32>, k: i32) -> i32 {
let (mut l, mut r) = (1, s.iter().sum::<i32>() / (k+1));
letmut ans =0;
while l <= r {
let m = l + (r-l)/2;
letmut cnt =0;
letmut sum =0;
for&x in&s {
sum += x;
if sum >= m {
cnt +=1;
sum =0;
}
}
if cnt >= k+1 {
ans = m;
l = m+1;
} else {
r = m-1;
}
}
ans
}
}