CJCoding With Joseph
15free / daySign inCreate account

Keep the K Largest Values With a Min Heap

Complete add(int score) and kthBest() so the Leaderboard keeps only the k highest scores it has ever seen, however many scores arrive.

Reminder: Java's PriorityQueue is a min heap. PriorityQueue<Integer> is the same array-backed heap you can build by hand: the smallest value sits on top, and every parent is no bigger than its children. peek() looks at the smallest value, poll() removes it, and adding or removing one value is cheap because it only sifts along one path of the tree instead of sorting everything again.

It sounds backwards, but a min heap is the right tool for keeping the LARGEST values. Keep at most k scores in it. The weakest of the kept scores is always on top, and it is exactly the one that should leave first: when a new score pushes the heap past k, poll() throws that weakest one away, so what stays behind is always the k best. The top of the heap is then the k-th best score.

Requirements: 1. add(int score) puts the score into best, then removes the smallest score whenever best holds more than k. 2. kthBest() returns -1 while fewer than k scores are kept, otherwise the k-th highest score (the smallest one kept), without removing it. 3. k is always at least 1. Do not change the constructor, size() or toString(), which prints the kept scores highest first.

Do NOT write a main method.

Expected Output:

Top 3: 90 85 70
70
3
Top 3: 95 90 85
85

= newline. The output ends with a newline — print one after the last line.

Hints4 available
Topics:
Data Structures & AlgorithmsHeaps
1
Tab to indent (Esc then Tab to move on) · Ctrl+Enter to run · Shift+Alt+F to format · Ctrl+Space to expand shortcuts (sysout, psvm, fori)

Your Output

Run your code to see the output here...

Test Cases

Run your code to see test case results.