โ† Back to Index

๐Ÿ“š Divide Chocolate โ€“ Java Cheat Sheet

๐Ÿ“Œ What Is It?

The Divide Chocolate problem involves dividing a chocolate bar (represented as an array of sweetness levels) into k + 1 pieces such that the minimum sweetness of the piece with the least sweetness is maximized. The goal is to solve this using binary search.

๐Ÿงฑ Pattern Template

class Solution {
    public int maximizeSweetness(int[] sweetness, int k) {
        int left = 1, right = 0;

        for (int sweet : sweetness) {
            right += sweet; // Total sweetness
        }

        while (left < right) {
            int mid = right - (right - left) / 2;

            if (canDivide(sweetness, k, mid)) {
                left = mid; // Try a larger minimum sweetness
            } else {
                right = mid - 1; // Try a smaller minimum sweetness
            }
        }

        return left;
    }

    private boolean canDivide(int[] sweetness, int k, int minSweetness) {
        int currentSweetness = 0, pieces = 0;

        for (int sweet : sweetness) {
            currentSweetness += sweet;

            if (currentSweetness >= minSweetness) {
                pieces++;
                currentSweetness = 0;

                if (pieces > k) {
                    return true;
                }
            }
        }

        return pieces > k;
    }
}

๐Ÿ“Š Time Complexity

โœ… Use Cases

๐Ÿ“˜ Common LeetCode Problems

๐Ÿงช Example: Divide Chocolate

Input: sweetness = [1,2,3,4,5,6,7,8,9], k = 5
Output: 6

Explanation:
- Divide the chocolate into [1,2,3], [4], [5], [6], [7,8,9].
- The minimum sweetness among these pieces is 6, which is maximized.

๐Ÿ’ก Pro Tips