Skip to the code
cf.
+25 XP

#601 Cheapest Way to Concatenate Chunks

medium

A build tool must concatenate several output chunks into one file. It joins two chunks at a time, and joining chunks of sizes x and y costs x + y (it reads and writes every byte). The joined chunk can be joined again later, in any order.

Write cheapestConcat(sizes) that returns the smallest total cost to end with a single chunk. With zero or one chunk there's nothing to join, so the cost is 0.

Example 1

Input: sizes = [2,4,3]
Output: 14

Join 2 and 3 (cost 5), then 5 and 4 (cost 9): 5 + 9 = 14.

Example 2

Input: sizes = [1,8,3,5]
Output: 30

Join 1 + 3 = 4, then 4 + 5 = 9, then 9 + 8 = 17: 4 + 9 + 17 = 30.

Constraints

  • 0 <= sizes.length <= 10000
  • 1 <= sizes[i] <= 1000
Saved in this browser

Run tries your code on the examples. Submit runs every test, including hidden edge cases, and solves the problem when they all pass.

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