THINK FIRST·CODE LATER

← All labs

Top-k and the k-th largest value

Problem

Read n integers and report the k largest of them and the k-th largest, using a min-heap that never holds more than k elements (java.util.PriorityQueue is allowed). Do not sort the whole input.

Input. The first line holds n and k. The next line(s) hold n integers (possibly negative, possibly repeated).

Output. If k < 1 or k > n (this includes n = 0), print exactly Invalid k. Otherwise print two lines:

Top k: v1 v2 ... vk
Kth largest: x

where v1 … vk are the k largest values in descending order and x is the k-th largest. Duplicates count separately: the 2 largest of 5 5 3 are 5 5, so the 2nd largest is 5.

Example.

Input:
7 3
7 2 9 4 9 1 6

Output:
Top 3: 9 9 7
Kth largest: 7

Write it here or in your IDE, then paste it. Compile and test it yourself before comparing. Your code stays in your browser — it is never sent to or stored on the server.