Loading...
Loading...
Loading...
A store has the sales count of n products. Print the k highest sales counts, from the highest to the lowest. Keep only k values in memory at a time, using a PriorityQueue.
Example
Input
6 3 50 20 90 10 70 40
Output
90 70 50
The three highest are 90, 70 and 50.
Try the problem first. Open one hint at a time.
Use a min-heap of size k: PriorityQueue<Integer> heap = new PriorityQueue<>();.
offer every count; whenever the size goes above k, poll the smallest. The heap then holds the k highest counts seen so far.
The heap polls smallest first, so collect the k values and print them in reverse.
Write your Java code, run it on the examples and submit it to hidden tests.
Solve in the editor