A log archiver concatenates log files into one. It can only join two files at a time, and joining files of sizes a and b costs a + b (it reads both and writes the result). The result is a new file of size a + b that can be joined again. Files can be joined in any order; it does not matter which two were next to each other.
Write two functions that take an array sizes of file sizes:
minMergeCost(sizes) returns the lowest possible total cost of joining all files into one.
mergePlan(sizes) returns one cheapest sequence of joins as an array of [smaller, larger] size pairs, in the order they happen, where each join takes the two smallest sizes available at that moment.
Rules:
Fewer than two files need no joins: the cost is 0 and the plan is [].
Sizes are non-negative safe integers (Number.isSafeInteger). If sizes is not an array of them, throw a TypeError.
Do not change sizes.
Arrays can hold 200,000 sizes. Finding the two smallest by scanning or re-sorting after every join is O(n²) and will not finish in time.