AlgoFrames

The k largest values

Standard · Write code · about 12 min

Return the k largest values of values, largest first. Build a max-heap, then run only k rounds of heap sort: each round takes the root.

Duplicates count separately, so [5, 5, 1] with k = 2 gives [5, 5].

Example 1

Input:

[[6,3,8,1,9,2,7],3]

Output:

[9,8,7]

After three rounds the last three cells hold 7, 8, 9.

Example 2

Input:

[[5,5,1],2]

Output:

[5,5]

Both 5s are returned.

Constraints

  • 0 ≤ values.length ≤ 10,000
  • 0 ≤ k ≤ values.length
  • Values are integers from -100,000 to 100,000

Learn the idea first: Heap sort, a visual lesson.

More Heap sort problems