How to approach this problem?


My naive implementation is getting TLE and the top submissions are completely unreadable by me.
Can anyone explain how this question will be solved?