


You are given an array/list ‘ARR’ of ‘N’ positive integers where each element describes the length of the stick. You have to connect all sticks into one. At a time, you can join any two sticks by paying a cost of ‘X’ and ‘Y’ where ‘X’ is the length of the first stick and ‘Y’ is the length of the second stick and the new stick we get will have a length equal to (X+Y). You have to find the minimum cost to connect all the sticks into one.
The first line of input contains an integer ‘T’, denoting the number of test cases.
The first line of each test case contains an integer ‘N’, representing the total number of sticks.
The second line of each test case contains ‘N’ space-separated integers denoting the length of each stick.
Output format:
For each test case, print the minimum cost to connect all the sticks into one by performing the above-mentioned operation.
Output for each test case is printed on a separate line.
Note:
You do not need to print anything. It has already been taken care of. Just implement the given function.
1 <= T <= 10
1 <= N <= 10^4
1 <= Val <= 5*10^3
Where ‘T’ represents the number of test cases, ‘N’ represents the number of sticks, and ‘Val’ represents the initial length of any stick.
Time Limit: 1 sec
2
3
2 4 3
4
1 8 3 5
14
30
For the first test case,
We have sticks of length {2, 4, 3}. First, connect sticks of length 2 and 3 to form a stick of length 5 and which gives a cost of 5. Now we have two sticks of length 5 and 4 each. Now we will connect sticks of length 5 and 4 to form one complete stick of length 9 which gives a cost of 9 and a total cost is 5 + 9 = 14.
For the second test case,
We have sticks of length {1, 8, 3, 5}. First, connect sticks of length 1 and 3 to form a stick of length 4 and which gives a cost of 4. Now we have sticks of length as {4, 8, 5}. Then connect sticks of length 4 and 5 to form a stick of length 9 and it gives a cost of 9. Now we have sticks of length as {9, 8}. Finally, connect the stick of length 8 and 9 which gives a cost of 17 and a total cost is 4 + 9 + 17= 30.
2
3
2 9 7
2
10 9
27
19
Can you solve this problem by finding two minimum lengths every time from the given lengths?
Approach:
Algorithm:
O(N*Log(N)), where ‘N’ is the total number of sticks.
Since we are traversing the array ‘ARR’ and inserting each element in the heap which will take O(Log(N)) time for insertion of each element giving a total time of O(N*Log(N)). Also, we are traversing the heap with ‘N’ elements and performing the pop operation which will take O(Log(N)) time giving a total time of O(N*Log(N)). Thus, overall time complexity will be O(N*Log(N)).
O(N), where ‘N’ is the total number of the sticks.
Since ‘N’ elements are stored in the heap, therefore, giving a space complexity of O(N).