Divide Chocolate Problem
Description
LeetCode Problem 1231.
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^41 <= sweetness[i] <= 10^5
Solution
Approach: Binary Search on the Answer
Turn the question around: for a given value x, can we cut the bar into k + 1 pieces that each have sweetness at least x? If we can, then we can also do it for any smaller x. So the answer, the largest x that works, can be found by binary search.
To check x, go from left to right and cut as soon as the current piece reaches x. Cutting as early as possible leaves as much as possible for the pieces after it, so this greedy makes the most pieces of at least x. If it makes k + 1 or more, x works: merge any extra pieces (and the leftover chunks at the end) into the last one, which only makes it sweeter. Our piece, the smallest, is then at least x.
The search range: x = 1 always works, since there are at least k + 1 chunks and each is at least 1. And no piece can be guaranteed more than total / (k + 1), the average. Search for the largest working value in between, with mid rounded up so the loop makes progress.
The total sweetness can reach 104 · 105 = 109, so in Java and C++ compute the midpoint as lo + (hi - lo + 1) / 2 instead of (lo + hi + 1) / 2, which could overflow.
Complexity: O(n log(S / (k + 1))) time, where S is the total sweetness, and O(1) extra space.
class Solution:
def maximizeSweetness(self, sweetness: List[int], k: int) -> int:
def can_get(x: int) -> bool:
# Greedily cut a piece as soon as it reaches x; we need k + 1 such pieces.
pieces = cur = 0
for v in sweetness:
cur += v
if cur >= x:
pieces += 1
cur = 0
return pieces >= k + 1
lo, hi = 1, sum(sweetness) // (k + 1) # every chunk is >= 1, so lo = 1 always works
while lo < hi:
mid = (lo + hi + 1) // 2
if can_get(mid):
lo = mid
else:
hi = mid - 1
return lo