Can anyone explain the approach?

I have read the editorial but yet not clear about the approach and the reason why it will work. Can anyone tell me the approach about how to start thinking of this problem? I am so confused about the approach.

Problem link

you can refer this video editorial for better understanding :slight_smile:
Atcoder Beginner Contest 221 Solutions || Problems A to E - YouTube