Problem-https://codeforces.com/gym/102263/problem/M

What’s Wrong?- Getting Wrong Answer with my approach on test case 3.

Here is my approach-- https://ideone.com/4h5VZJ

I tried various test cases but i couldn’t find where it could possibly go wrong.

P.S-I also tried bruteforce way but it was giving me time limit exceeded on test case 3.

Can anyone help with this problem and their approach?