This problem is from Codechef july long challenge. The logic behind the solution is straightforward but not most of the solution could pass through all the test cases. Because the test cases were made quite tight.
However right use of proper data structure would help you in this situation.
I hope I was able to explain in the video properly.
Checkout my channel for bunch of similar other videos, ==
https://youtube.com/channel/UC6uQdd7kLLOdlHSVklhV7Cw/videos?d=ud
Problem link == https://www.codechef.com/JULY20A/problems/PTMSSNG
Submission link == https://www.codechef.com/viewsolution/35174920
Video link on Sets in C++ == https://www.youtube.com/watch?v=8NKGt8slKy0&t=1s