Comments

i don't have any link, it was asked in offline competition in my university.

thanks for the approach, if you figured out the optimal approach you are thinking about then do share.

that's I thought, it works fine. I think there are more optimised approach for this question, if you find it then do share.

Great, if you like, could you elaborate your logic bit more, I know binary search but i am not well verse with it. If you could state the logic more, it would be great help for me.

I think your approach is O(n^2) approach, do you have any better optimised approach, do share.