Minimum Cost to Merge
You are provided a two-dimensional integer array lists. Every lists[i] contains a sequence of numbers ordered in non-decreasing fashion.
Your objective is to combine all these lists into one single ordered list. In each step, you can select any two distinct lists, say a and b, and fuse them.
The toll you pay for fusing a and b is calculated as: the size of a plus the size of b plus the absolute difference between the median of a and the median of b. When fused, a and b are deleted from the collection, and the freshly combined ordered list takes their place.
You continue this fusion until a solitary list remains. The median is the number standing exactly in the middle of a sorted collection. If the collection has an even count of numbers, the median falls on the left of the exact center.
Return the absolute lowest total toll needed to fuse every list.
Example 1:
Input: lists = [[2, 2], [5], [10, 10, 10]]
Output: 20
Explanation: We start by merging [2, 2] (median 2) and [5] (median 5). The cost is their combined length (3) plus the absolute difference of their medians (3), which equals 6. The newly merged list is [2, 2, 5], which has a median of 2. Next, we merge this new list with [10, 10, 10] (median 10). The cost is their combined length (6) plus the absolute difference of their medians (8), giving a cost of 14 for this step. The total minimum accumulated cost is 6 + 14 = 20.
Example 2:
Input: lists = [[1, 5], [4, 8], [9, 10]]
Output: 18
Explanation: First, we optimally merge [1, 5] (median 1) and [4, 8] (median 4). The cost is their length sum (4) plus the median difference (3), equating to 7. The resulting list is [1, 4, 5, 8], which has a new left-middle median of 4. We then merge this with [9, 10] (median 9). This operation costs the combined length (6) plus the median difference (5), yielding 11. Accumulating these step costs gives our optimal minimum total of 7 + 11 = 18.
Now Your Turn!
Pick the correct output for the given inputInput: lists = [[0, 0], [0, 0, 0]]
Still unsure what the problem is asking ?
Let’s go through a few more examples, step by step, to make it clearer.
Constraints:
- 2 <= lists.length <= 12
- 1 <= lists[i].length <= 500
- -109 <= lists[i][j] <= 109
- lists[i]Â is sorted in non-decreasing order.
- The sum of lists[i].length will not exceed 2000.