Skip to content

Instantly share code, notes, and snippets.

@jhidajat
Created May 4, 2022 04:33
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jhidajat/be3ab1fa74c3bcd05bdce8765c317670 to your computer and use it in GitHub Desktop.
Save jhidajat/be3ab1fa74c3bcd05bdce8765c317670 to your computer and use it in GitHub Desktop.
"""
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.
"""
def maximizeSweetness(self, sweetness: List[int], k: int) -> int:
def _can_reach_target_min_with_at_least_k_plus_one_subset(sweetness, target):
curr_sum = 0
count = 0
for s in sweetness:
curr_sum += s
if curr_sum >= target:
curr_sum = 0
count += 1
return count >= k+1
l, r = min(sweetness), sum(sweetness)//(k+1)
while l <= r:
if l == r:
return r
mid = l+(r-l)//2+1
if _can_reach_target_min_with_at_least_k_plus_one_subset(sweetness, mid):
l=mid
else:
r=mid-1
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment