equidlis easy practice

i am not getting the (quick)logic for this problem: EQIDLIS Problem - CodeChef
my solution was: CodeChef: Practical coding for everyone
(getting TLE)
already checked the editorial.please help me solve this problem…

@hitesh091 : You are sorting every time you make a exchange which is very costly . Sorting is n log n and quick sort can be n ^ 2 . You should maintain a balanced tree of number of idlis of each student . Get maximum and minimum in log n time each and insert new numbers in log n time each , taking a time of 4 * log n for each exchange .

checked other solutions but unable to understand the logic…