## # 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], , , , 
``````

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]
``````

### # Solution

Approach 1: DP (TLE in python). Let `divide[i][k]` be the max total of the min chunk, dividing into k chunks using the first i items. Time: O(K * N^2).

Approach 2: binary search -- for different min sweetnesses, find last value whose number of chunks divided >= k. Time: `O(Nlog(sum(sweetness)))`.

### # Code (Python)

Approach 1:

``````    def maximizeSweetness(self, sweetness, K):
# DP (TLE in python). divide[i][k]: max total of the min chunk, dividing into k chunks using the first i items, i >= k
# divide[i][k] = max(min(divide[c][k-1], sum(sweetness[c:i]))) across all c where k-1 <= c <= i-2
# init: divide[i][k] = min(sweetness[:i]) if i == k, divide[i] = sum(sweetness[:i])
# time: O(K * N^2)
cum_sum = [sweetness]
for i in range(1, len(sweetness)):
cum_sum.append(sweetness[i] + cum_sum[-1])
K = K + 1
divide = [ * (K + 1) for _ in range(len(sweetness) + 1)]
for k in range(1, K + 1):
for i in range(k, len(sweetness) + 1):
if k == i:
divide[i][k] = min(sweetness[:i])
elif k == 1:
divide[i][k] = sum(sweetness[:i])
else:
for c in range(k - 1, i):
divide[i][k] = max(divide[i][k], min(divide[c][k-1], cum_sum[i-1] - cum_sum[c-1]))
return divide[-1][-1]
``````

Approach 2:

``````    def maximizeSweetness(self, sweetness, K):
# binary search -- find last value whose number of chunks divided >= k: [>k, >k, ..., =k, =k, <k, ...]
# time: O(Nlog(sum(sweetness)))
k = K + 1
lo, hi = min(sweetness), sum(sweetness)
result = hi
while lo < hi:
mid = (lo + hi) // 2
# trick to find last: use mid + 1 to prevent off by 1 error
num_shares = self._num_shares(mid + 1, sweetness, k)
if num_shares:
lo = mid + 1
else:
hi = mid
return lo
# OR:
#while lo <= hi: # make hi > lo eventually
#    mid = (lo + hi) // 2
#    num_shares = self._num_shares(mid, sweetness, k)
#    if num_shares:
#        lo = mid + 1
#    else:
#        hi = mid - 1
#return hi
``````

Approach 1:

Approach 2: