Codeforces div 2 ques 4...please help

Here is the problem link-Problem - D - Codeforces
Can anyone tell me the right approach…my approach failed on test case 10.

Here is a nice editorial - Codeforces Round #613 (Div. 2) Editorial - Codeforces
xD