Skip to content

Commit f920d2f

Browse files
committed
Divide Chocolate
1 parent 4af44d0 commit f920d2f

File tree

1 file changed

+54
-0
lines changed

1 file changed

+54
-0
lines changed

1231-divide-chocolate.py

+54
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,54 @@
1+
"""
2+
Problem Link: https://leetcode.com/problems/divide-chocolate/
3+
4+
You have one chocolate bar that consists of some chunks. Each chunk has its own sweetness given by the array sweetness.
5+
You want to share the chocolate with your K friends so you start cutting the chocolate bar into K+1 pieces using K cuts,
6+
each piece consists of some consecutive chunks.
7+
Being generous, you will eat the piece with the minimum total sweetness and give the other pieces to your friends.
8+
Find the maximum total sweetness of the piece you can get by cutting the chocolate bar optimally.
9+
10+
Example 1:
11+
Input: sweetness = [1,2,3,4,5,6,7,8,9], K = 5
12+
Output: 6
13+
Explanation: You can divide the chocolate to [1,2,3], [4,5], [6], [7], [8], [9]
14+
15+
Example 2:
16+
Input: sweetness = [5,6,7,8,9,1,2,3,4], K = 8
17+
Output: 1
18+
Explanation: There is only one way to cut the bar into 9 pieces.
19+
20+
Example 3:
21+
Input: sweetness = [1,2,2,1,2,2,1,2,2], K = 2
22+
Output: 5
23+
Explanation: You can divide the chocolate to [1,2,2], [1,2,2], [1,2,2]
24+
25+
Constraints:
26+
0 <= K < sweetness.length <= 10^4
27+
1 <= sweetness[i] <= 10^5
28+
"""
29+
class Solution:
30+
def maximizeSweetness(self, sweetness: List[int], K: int) -> int:
31+
start, end = min(sweetness), sum(sweetness)//(K+1)
32+
ans = None
33+
while start <= end:
34+
mid = (start+end)//2
35+
print(start, end, mid)
36+
if self.canDivide(sweetness, K+1, mid):
37+
ans = mid
38+
start = mid + 1
39+
else:
40+
end = mid - 1
41+
return ans
42+
43+
44+
def canDivide(self, sweetness, k, m):
45+
cuts, num = 0, 0
46+
for val in sweetness:
47+
num += val
48+
if num >= m:
49+
cuts += 1
50+
num = 0
51+
if cuts >= k:
52+
return True
53+
54+
return False

0 commit comments

Comments
 (0)