Minimum Cost to Merge Sorted Lists
hard · 34% accepted · 41 likes · top 11%
array · two pointers · binary search · dynamic programming · bit manipulation
Description
You are given a 2D integer array lists, where each lists[i] is a non-empty array of integers sorted in non-decreasing order.
You may repeatedly choose two lists a = lists[i] and b = lists[j], where i != j, and merge them. The cost to merge a and b is:len(a) + len(b) + abs(median(a) - median(b)), where len and median denote the list length and median, respectively.
After merging a and b, remove both a and b from lists and insert the new merged sorted list in any position. Repeat merges until only one list remains.
Return an integer denoting the minimum total cost required to merge all lists into one single sorted list.
The median of an array is the middle element after sorting it in non-decreasing order. If the array has an even number of elements, the median is the left middle element.
Solution