Merging a sorted list consisting of K elements with a sorted list consisting of L elements takes (K + L) milliseconds(ms). The time required to merge more than two lists into one final list depends on the order in which the merges are performed.
For example, consider the following three lists:
They can be merged into one final sorted list in three different ways:
The time needed to perform the above merges are respectively:
The first schema is the fastest(1700ms).
If there are more than three lists to merge, there are even more merge strategies to consider. When the number of lists is fewer than two, no merges are performed and the total merge time is assumed to be 0.
Write a function:
class Solution { public int solution(int[] A); }
that, given an array A of length N describing the lengths of N lists, returns the shortest time (measured in milliseconds) required to merge these lists into one.
For example, given array A consisting of three elements such that:
A[0] = 100 A[1] = 250 A[2] = 1000
the function should return 1700, as explained above.
Write an efficient algorithm for the following assumptions:
My Attempt:
This was my solution though it was not accepted. I sorted the list sizes and merged from lowest to highest same as the example merge in the question. Got 14% workability.
class Solution {
public int solution(int[] A) {
if (A.length < 2) {
return 0;
}
Arrays.sort(A);
int total = 0;
int current = A[0];
for (int i = 1; i < A.length; i++) {
total += current + A[i];
current = current + A[i];
}
return total;
}
}