> or is there some other technique?
Yes, you use the clues in the question to figure out a better approach.
"Tag(s): Ad-Hoc, Data Structures, Heap, Heaps/Priority Queues, Medium-Hard, Trees"
> My approach is giving tle.
Well yes, stupid brute-force "try every combination" approaches will almost always result in time limit exceeded because that's a dumb way to solve a problem. Anyone can solve these problems if they're allowed to just post the first dumb answer that comes to mind.
The whole point of the exercise is to use those advanced data structures to quickly prune away whole sets of data from being tested.
Before you even open your IDE and start typing
#include<iostream> you need to have solved this problem on paper.
Step 1, solve this on paper by running your algorithm by hand.
At some point, you'll either
- get bored and start to think about the problem a bit more.
- suddenly realise there is a pattern you can exploit to make a better algorithm.