Codeforces div 2 ques 4...please help

Here is the problem link-https://codeforces.com/contest/1285/problem/D
Can anyone tell me the right approach…my approach failed on test case 10.

Here is a nice editorial - https://codeforces.com/blog/entry/72950
xD