Divide Chocolate

Cut the chocolate bar into k+1 contiguous pieces maximizing the minimum piece sum — binary search on the answer.

Hard
Time O(n log S) Space O(1)
LeetCode
4 min read
binary-search greedy

Problem#

Cut sweetness (array of integers) into k+1 contiguous parts. Maximize the smallest part sum.

Examples#

  • sweetness = [1,2,3,4,5,6,7,8,9], k = 56

Constraints#

  • 1 <= sweetness.length <= 10^4, 0 <= k < sweetness.length.

Approach#

Binary search on the answer target. Predicate: “can we make at least k+1 cuts each with sum ≥ target?” — greedy scan, accumulate until reaching target, then start a new piece.

Solution#

Divide Chocolate
class Solution {
public:
int maximizeSweetness(vector<int>& sweetness, int k) {
auto feasible = [&](int t) {
int cuts = 0, cur = 0;
for (int x : sweetness) {
cur += x;
if (cur >= t) { ++cuts; cur = 0; }
}
return cuts >= k + 1;
};
int lo = *min_element(sweetness.begin(), sweetness.end());
int hi = accumulate(sweetness.begin(), sweetness.end(), 0) / (k + 1);
while (lo < hi) {
int mid = lo + (hi - lo + 1) / 2;
if (feasible(mid)) lo = mid;
else hi = mid - 1;
}
return lo;
}
};

Editorial#

Dual of Split Array Largest Sum — there we min-max, here we max-min, but the structure is identical: binary search the answer with a monotone greedy predicate.

Complexity#

  • Time: O(n log S).
  • Space: O(1).

Concept revision#

Search ESC

Keyboard shortcuts

Shortcuts are disabled while typing in inputs.