Can anyone explain the solution to the problem IEMCO6C?

Link: https://www.codechef.com/IEMCO6/problems/IEMCO6C

**PS:
I have seen some solutions which uses two for loops to find the next right index as given in the problem.
But worst case operations will be 5*10^8 , wont the solution get TLE?**