https://codeforces.com/contest/1437/problem/B

https://codeforces.com/contest/1437/problem/B
Can anyone explain how to solve this problem. I understand what we are doing in the code(I saw other peoples solution and the editorial) but not why we are doing it.