Skip to content

Latest commit

 

History

History

1231

Folders and files

NameName
Last commit message
Last commit date

parent directory

..
 
 

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.

 

Example 1:

Input: sweetness = [1,2,3,4,5,6,7,8,9], k = 5
Output: 6
Explanation: You can divide the chocolate to [1,2,3], [4,5], [6], [7], [8], [9]

Example 2:

Input: sweetness = [5,6,7,8,9,1,2,3,4], k = 8
Output: 1
Explanation: There is only one way to cut the bar into 9 pieces.

Example 3:

Input: sweetness = [1,2,2,1,2,2,1,2,2], k = 2
Output: 5
Explanation: You can divide the chocolate to [1,2,2], [1,2,2], [1,2,2]

 

Constraints:

  • 0 <= k < sweetness.length <= 104
  • 1 <= sweetness[i] <= 105

Companies:
Google, Facebook

Related Topics:
Array, Binary Search

Similar Questions:

Solution 1. Binary Answer

// OJ: https://leetcode.com/problems/divide-chocolate/
// Author: github.com/lzl124631x
// Time: O(Nlog(M/(k+1))) where `N` is the length of `A` and `M` is the sum of elements in `A`.
// Space: O(1)
class Solution {
public:
    int maximizeSweetness(vector<int>& A, int k) {
        long N = A.size(), L = 0, R = accumulate(begin(A), end(A), 0L) / (k + 1);
        auto valid = [&](int goal) {
            for (int i = 0, sum = 0, cnt = 0; i < N; ++i) {
                sum += A[i];
                if (sum >= goal) {
                    sum = 0;
                    if (++cnt >= k + 1) return true;
                }
            }
            return false;
        };
        while (L <= R) {
            long M = (L + R) / 2;
            if (valid(M)) L = M + 1;
            else R = M - 1;
        }
        return R;
    }
};