# 1231.Divide-Chocolate

## 1231. Divide Chocolate

## 题目地址

<https://leetcode.com/problems/divide-chocolate/>

## 题目描述

```
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 <= 10^4
1 <= sweetness[i] <= 10^5
```

## 代码

### Approach #1 Binary Search

```java
class Solution {
  public int maximizeSweetness(int[] sweetness, int K) {
    int l = 0, r = Arrays.stream(sweetness).sum() / (K + 1);
    while (l < r) {
      int mid = l + (r - l + 1) / 2;
      int cnt = 0;
      int sum = 0;
      for (int i = 0; i < sweetness.length; i++) {
        sum += sweetness[i];
        if (sum >= mid) {
          sum = 0;
          cnt++;
        }
      }

      if (cnt >= K + 1) {
        l = mid;
      } else {
        r = mid - 1;            // ???
      }
    }

    return l;
  }
}
```


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://wentao-shao.gitbook.io/leetcode/array/1231.divide-chocolate.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
