Skip to the code
+25 XP

#542 Cheapest Bundle Merge

medium

A build tool has a row of JavaScript chunks with sizes sizes, in load order. It can merge two neighboring chunks into one, and a merge costs the combined size of the two chunks. It keeps merging neighbors until a single bundle is left.

Write cheapestMerge(sizes) that returns the smallest total cost of all the merges. A single chunk needs no merging and costs 0.

Example 1

Input: sizes = [3,1,2]
Output: 9

Merge 1 and 2 (cost 3), then 3 and 3 (cost 6). Merging 3 and 1 first costs 4 + 6 = 10.

Example 2

Input: sizes = [5,5]
Output: 10

One merge of both chunks.

Constraints

  • 1 <= sizes.length <= 100
  • 1 <= sizes[i] <= 1000
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).