Skip to the code
+50 XP

#602 Bundle Chunks k at a Time

hard

A faster bundler can join up to k chunks in one step. Each step picks between 2 and k chunks and joins them into one; the cost of a step is the total size of the chunks it joins.

Write cheapestBundle(sizes, k) that returns the smallest total cost to end with a single chunk. With zero or one chunk, the cost is 0.

Example 1

Input: sizes = [1,2,3,4,5], k = 3
Output: 21

Join 1 + 2 + 3 = 6 (cost 6), then 4 + 5 + 6 = 15 (cost 15): 21.

Example 2

Input: sizes = [1,2,3,4], k = 3
Output: 13

Join just 1 + 2 = 3 first (cost 3), then 3 + 3 + 4 = 10: 13. Joining three at first would cost 6 + 10 = 16.

Constraints

  • 0 <= sizes.length <= 2 * 10^5
  • 1 <= sizes[i] <= 1000
  • 2 <= k <= 20
Saved in this browser

Run tries your code on the examples. Submit runs every test, including hidden edge cases and big inputs that check your code is fast enough, and solves the problem when they all pass.

Ctrl + Enter runs, Ctrl + Shift + Enter submits (⌘ on a Mac).