Divide Chocolate - Problem

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.

Input & Output

Example 1 — Basic Case
$ Input: sweetness = [1,2,3,4,5,6,7,8,9], k = 2
Output: 14
💡 Note: Optimal cuts create pieces [1,2,3,4,5] (sum=15), [6,7] (sum=13), [8,9] (sum=17). You get the minimum piece with sweetness 13. But better cuts [1,2,3,4] (sum=10), [5,6,7] (sum=18), [8,9] (sum=17) give minimum 10. The optimal is actually [1,2,3,4,5,6] (sum=21), [7] (sum=7), [8,9] (sum=17) → min=7. After trying all possibilities, the maximum minimum is 14.
Example 2 — Small Array
$ Input: sweetness = [5,6,7,8,9,1,2,3,4], k = 8
Output: 1
💡 Note: With k=8 cuts on 9 elements, we create 9 pieces of 1 element each. The minimum will be the smallest element, which is 1.
Example 3 — No Cuts Possible
$ Input: sweetness = [1,2,2,1,2,2,1,2,2], k = 2
Output: 5
💡 Note: Best cuts create pieces like [1,2,2] (sum=5), [1,2,2] (sum=5), [1,2,2] (sum=5). Each piece has sweetness 5, so minimum is 5.

Constraints

  • 1 ≤ sweetness.length ≤ 104
  • 1 ≤ sweetness[i] ≤ 105
  • 0 ≤ k ≤ sweetness.length - 1

Visualization

Tap to expand
Divide Chocolate - Greedy Approach INPUT Chocolate Bar (9 chunks) 1 2 3 4 5 6 7 8 9 sweetness = [1,2,3,4,5,6,7,8,9] k = 2 (friends) Need k+1 = 3 pieces Total sweetness: 1+2+3+4+5+6+7+8+9 = 45 GOAL Maximize the minimum piece you keep ALGORITHM STEPS 1 Binary Search Setup lo=1, hi=45/3=15 2 Try mid=8 Can we get 3 pieces >= 8? 3 Greedy Check Count pieces greedily 4 Binary Search Narrow to find max min Testing mid = 14: 1+2+3+4+5 =15 (OK) 6+7+8 =21 (OK) 9 =9 (min) 3 pieces OK -- try higher Final answer: 14 FINAL RESULT Optimal Cutting: YOUR PIECE (minimum) 1 2 3 4 5 = 15 CUT 1 Friend 1's Piece 6 7 = 13 CUT 2 Friend 2's Piece 8 9 = 17 OUTPUT 14 Key Insight: Binary search on the answer: Instead of trying all possible cuts, we binary search on the minimum sweetness. For each candidate value, we greedily check if we can form k+1 pieces where each has at least that sweetness. Time complexity: O(n * log(sum)) where sum is total sweetness. Much better than trying all cut combinations! TutorialsPoint - Divide Chocolate | Greedy + Binary Search Approach
Asked in
Google 12 Facebook 8 Amazon 6
23.4K Views
Medium Frequency
~25 min Avg. Time
890 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen