Cheating On Queue

Code CHef Question !
I am not getting the approach for this ! as simple brute force takes O(N^2) and N is 10^5 and Time limit is 1sec.
Question Link:
https://www.codechef.com/MARCH19B/problems/CHONQ