Input: ‘N’ = 3, ‘HEIGHTS’ = [2, 3, 6]
Output: 3
Step 1 = [2, 3, 3],
Step 2 = [2, 3, 2],
Step 3 = [2, 2, 2].
Hence, the total number of steps required is 3.
The first line will contain the integer 'T', denoting the number of test cases.
The first line of each test case contains an integer ‘N’ denoting the length of the array ‘HEIGHTS’.
The second line of each test case contains ‘N’ integers denoting the heights of the piles of boxes.
For each test case, return the number of steps required to bring the height of the entire pile to the same height as the pile with minimum height.
You don't need to print anything. It has already been taken care of. Just implement the given function.
1 <= T <= 10
1 <= N <= 10^5
1 <= A[i] <= 10^5
Time Limit: 1 sec
In the naive approach, First, we push the height of each pile into the max heap. The top of the max heap contains the pile with the maximum height. We will extract all the piles from the max heap with a height equal to the maximum height and store them in an array ‘ALLCURMAX’. Then we will change the height of all the piles in ‘ALLCURMAX’ from maximum height to the next maximum height and then push them back into the max heap. Let the number of piles with maximum height be ‘X.’ Then we increment the total number of steps by ‘X’ because we need to change the height one by one. We will keep doing it iteratively unless all the piles in the max heap have the same height.
First, we need to sort the array. Then we traverse the array in reverse. For each pile in sorted order, we will try to find the number of steps required to make the height of this pile equal to the height of the pile with minimum height. To do so, we need to know how many intermediate heights it will be changed to. We can find the number of the intermediate by finding the number of distinct heights between the minimum height and the height of the pile.
For example, if heights = [2, 3, 4, 5], the pile with height ‘5’ will have (3, 4) as intermediate heights. The number of distinct heights between 2 and 5 is also (3, 4).
We can calculate the intermediate heights by using a hashtable. The sum of the intermediate heights of all piles will give us the required steps.
The steps are as follows:-