Merge Files K at a Time at the Lowest Total Cost

Implement minMergeCost

A backup tool can merge between 2 and k files into one file in a single step. Merging costs the total size of the files it combines, and the result is one file of that size. Given the sizes of the files, find the minimum total cost to end up with a single file.

Just as with pairwise merging, the smallest files should be merged first because every merged file is charged again in later merges. The wrinkle is the number of files: if a full k-way merge can't finish the job exactly, one merge must be smaller. Padding the heap with zero-size files makes every merge a clean k-way merge without changing the cost.

Example 1:

Input: files = [6,2,9,4], k = 3

Output: 27

Example 2:

Input: files = [5,5,5,5], k = 2

Output: 40

Example 3:

Input: files = [12], k = 4

Output: 0

+ 9 hidden test cases run on Submit.

Constraints:

  • ●1 ≤ files.length ≤ 40, 2 ≤ k ≤ 6
  • ●1 ≤ files[i] ≤ 500
  • ●One merge combines between 2 and k files into a single file whose size is their total; the merge costs that total size
  • ●Merge until one file remains; return the minimum total cost (0 if there is already one file)

files =

[6, 2, 9, 4]

k =

3