HardBinary SearchArrayGreedy

1 approach, code in every language

Problem description

You have a chocolate bar described by an array where each value is the sweetness of one consecutive chunk. You want to share it with k friends, so you make k straight cuts between chunks, producing k + 1 contiguous pieces. Every piece keeps its chunks together, and the sweetness of a piece is the sum of the chunks inside it.

Being generous, you always take the piece with the least total sweetness. Choose the cuts so that this smallest piece is as sweet as possible, and return that maximum achievable minimum sweetness.

Example 1

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

Output: 6

Cutting into pieces [1,2,3], [4,5], [6], [7], [8], [9] gives sweetness 6, 9, 6, 7, 8, 9. The weakest piece is 6, and no set of six pieces can raise that floor higher.

Example 2

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

Output: 1

With 8 cuts every chunk becomes its own piece, so the smallest piece is simply the smallest chunk, which is 1.

Constraints

  • 0 <= k < sweetness.length <= 10^4
  • 1 <= sweetness[i] <= 10^5

After the pattern

Now solve one you haven't seen.

Reading a pattern isn't the same as using it. The practice set has 1,194 original problems on the same techniques, each graded in your browser.

1,194 problems · 15,062 graded tests · free