⚡Flashcard Drill➔
NeetCode #270LC-1231HardBinary SearchNC Algo100
← Back to All Problems

#270 · #1231 · Divide Chocolate(分享巧克力)

📌 Problem Statement & Constraints

You have one chocolate bar with pieces of sweetness sweetness[i]. You will share it with k friends, so you cut the bar into k + 1 pieces, each a contiguous segment. You keep the piece with the minimum total sweetness. Return the maximum sweetness you can keep. Constraints: 1 <= k < sweetness.length <= 10^4, 1 <= sweetness[i] <= 10^5.

💡 Core Algorithmic Approaches

  1. Binary search on the answer: the predicate "can we make at least k + 1 pieces each with sweetness at least c" is monotone in c.
  2. The upper bound is sum(sweetness) / (k + 1), since the pieces must average at most that.
  3. For a given c, greedily cut whenever the running sum reaches c, and count the pieces.
  4. Feasible when the count is at least k + 1. Use the upper-biased midpoint since we want the maximum feasible value.

💻 Benchmark Python3 Implementation

class Solution:
    def maximizeSweetness(self, sweetness: List[int], k: int) -> int:
        lo, hi = 1, sum(sweetness) // (k + 1)
        while lo < hi:
            mid = (lo + hi + 1) // 2   # upper-biased: maximise
            pieces = 0
            cur = 0
            for s in sweetness:
                cur += s
                if cur >= mid:
                    pieces += 1
                    cur = 0
            if pieces >= k + 1:
                lo = mid               # feasible -> try larger
            else:
                hi = mid - 1
        return lo

⚡ Complexity Deep Dive

⏱️ Time Complexity
O(n log(sum / k)): each predicate is O(n).
💾 Space Complexity
O(1): a few scalars.

⚠️ Interview Pitfalls & Follow-ups

  • Using the lower-biased midpoint: with lo = mid on feasibility, the upper bias is required to avoid an infinite loop.
  • Requiring exactly k + 1 pieces: making more pieces is also fine, since they can be merged; the condition is >= k + 1.
  • Setting the upper bound to sum(sweetness): the average bound sum // (k + 1) is much tighter.
  • Sorting the pieces: the bar must be cut into contiguous segments, so the order is fixed.
⚡
Test muscle memory on this topic via 3-Layer Flashcards
Active Recall: Mentally formulate Prompt ➔ Math Derivation ➔ Benchmark Implementation in 3 minutes.
🎯 Drill This Card Now➔

🧩 Related Binary Search Problems

中文速览与面试要点

分享巧克力

你有一大块巧克力,它由一些甜度不完全相同的小块组成。我们用数组 sweetness 来表示每一小块的甜度。你打算和 K 名朋友一起分享这块巧克力,所以你需要将切割 K 次才能得到 K + 1 块,每一块都由一些 连续 的小块组成。为了表现出你的慷慨,你将会吃掉 总甜度最小 的那一块,并将其余几块分给你的朋友们。请找出你所能得到的巧克力的 最大总甜度 。约束:1 ≤ k ≤ sweetness.length ≤ 10^4;1 ≤ sweetness[i] ≤ 10^5。

核心要点

  • 二分答案(标准解) :二分「最小块甜度的下界 min_s 」,判定「能否切出至少 k+1 块,每块甜度都 ≥ min_s」。
  • 单调性 : min_s 越小越容易满足,因此可以二分。
  • 判定函数 :贪心累加,一旦当前段甜度 ≥ min_s 就切一刀并重新计数。返回可切出的段数。
  • 答案范围 : [1, sum(sweetness) // (k+1)] 。上界是「平均分配」时的甜度。
  • 二分模板 :本题求 最大 可行值,因此用 mid = (l + r + 1) // 2 配合 l = mid (向上取整模板,避免死循环)。

常见陷阱

  • 用 mid = (l + r) // 2 配合 l = mid :会死循环(当 r = l + 1 时 mid 恒为 l)。求「最大可行值」必须用向上取整的 mid。
  • 判定条件写成 pieces == k + 1 :贪心切出的段数可能多于 k+1(若 min_s 很小),应判断 &gt;= k + 1 。
  • 上界写成 sum(sweetness) :二分次数变多;上界取 sum // (k+1) 更紧且正确(不可能超过平均值)。
  • 忘记 k + 1 的段数 :K 个朋友 + 自己 = k+1 块。
  • 下界写成 0 :甜度都是正数,最小块至少为 1;写 0 虽不影响正确性但会多一次无效迭代。

参考实现

class Solution:
    def maximizeSweetness(self, sweetness: list[int], k: int) -> int:
        def can_split(min_s: int) -> bool:
            """能否切出至少 k+1 块,每块甜度 >= min_s。"""
            pieces = 0
            cur = 0
            for s in sweetness:
                cur += s
                if cur >= min_s:
                    pieces += 1
                    cur = 0
            return pieces >= k + 1

        l, r = 1, sum(sweetness) // (k + 1)
        while l < r:
            mid = (l + r + 1) // 2          # 向上取整,配合 l = mid
            if can_split(mid):
                l = mid                     # 可行 -> 尝试更大的下界
            else:
                r = mid - 1
        return l