Max Game
Posted: 11 Oct, 2020
Difficulty: Easy
You are given 'N' numbers and you have to play a game using them. In one move you have to pick any two numbers 'A' and 'B' and replace them by their sum 'A+B'. Doing this gives you a penalty of 'A+B'. Note that the count of elements reduces by 1 every time you take 2 numbers and replace them by their sum. The game ends when there is only one element left. Your task is to minimise the penalty during the game.
You need to return the minimum possible penalty you can have when the game ends.
Input format:
The first line of input contains an integer 'T' denoting the number of queries or test cases.
The first line of every test case contains an integer 'N' denoting the count of numbers.
The second line of every test case contains 'N' single space-separated integers representing the numbers given to you initially.
Output format:
For each test case, return the minimum possible penalty in a separate line.
Note:
You do not need to print anything, it has already been taken care of. Just implement the given function.
Constraints:
1 <= T <= 5
1 <= N <= 10^5
1 <= X[i] <= 10^6
Time limit: 1 second
Approach 1
- The idea is to keep only the required elements in the vector/array. Let the given array be { 3, 4, 5, 4}.
- We pick the 2 smallest elements i.e 3 and 4 in the above example and replace them with their sum. The above array hence becomes {5, 4, 7}.
- Along with this, we also maintain the penalty variable and keep on updating it. Initial value of the penalty will be 0. After we perform step 2, the penalty becomes 4+3=7.
- In the same way, we repeat the steps 2 and 3 until the size of the vector/ array becomes 1. In the example given above, from {5, 4, 7}, the 2 smallest elements are 4 and 5. The array becomes {7, 9} and penalty becomes 7 + 4 + 5 = 16. Then again, the two smallest elements are 7 and 9. Thus, the array becomes {16} and the penalty becomes 16 + 16 = 32. Now, we stop iterating as the size of the array becomes 1.
Approach 2
- The idea is to work with the min priority queue.
- Insert all the numbers into the queue.
- Till the size of the queue becomes 1, extract 2 numbers from the queue. Note that they will obviously be the 2 smallest numbers. Now, just push the sum of 2 numbers into the queue.
- Keep on calculating the penalty while performing step 3.
SIMILAR PROBLEMS
One Odd Occurring
Posted: 17 Apr, 2022
Difficulty: Easy
Min Heap
Posted: 5 May, 2022
Difficulty: Moderate
Left Rotate an Array by One
Posted: 17 May, 2022
Difficulty: Easy
Largest Element in the Array
Posted: 17 May, 2022
Difficulty: Easy
Matrix Boundary Traversal
Posted: 20 May, 2022
Difficulty: Easy