Problem 96
Kth Largest Element
Medium · 20 pts · Array, Sorting, Heap
Problem
You are given an array of N integers and an integer K. Print the K-th largest element: the element at position K when the array is sorted in descending order. Duplicates count separately, so in 5 5 4 the 2nd largest is 5. Sorting works in O(N log N). Faster options are a min-heap of size K (the top is the answer after processing all elements) or the quickselect algorithm, which runs in O(N) on average.
Input
First line: integers N and K. Second line: N space-separated integers.
Output
Print the K-th largest element.
Constraints
1 <= K <= N <= 100000; -10000 <= A[i] <= 10000
Example input
6 2 3 2 1 5 6 4
Example output
5
Explanation
3 2 1 5 6 4 sorted in descending order is 6 5 4 3 2 1. The 2nd element in that order is 5.