USE A MAX HEAP. Since Python doesn’t support max heaps fully (they do have a few private methods for max heaps, they are very unstable and are recommended not to use - it’s not even in their documentation). So I used Java PriorityQueue<Integer>
Add all elements to the queue, and they will be sorted in a ascending manner. Then maxHeap.poll()
the first two elements, check the conditions and maxHeap.offer()
them to the queue.
Do this until maxHeap.size() > 1
Code:
Java
— A