#C14613. K Largest Elements
K Largest Elements
K Largest Elements
Given a list of integers and an integer k, your task is to output the k largest elements from the list, sorted in descending order. If k is less than or equal to 0, or if the list is empty, output an empty line. In the event that k is greater than the number of elements in the list, simply return all the elements sorted in descending order.
This problem requires an efficient solution capable of processing lists with up to one million elements. An optimal approach uses a heap data structure with a time complexity of \(O(n \log k)\), which is particularly suitable when \(k\) is much smaller than \(n\). The use of a min-heap which maintains the top k elements will ensure that the solution scales well to large inputs.
Example:
Input: 6 3 1 5 2 4 6 3</p>Output: 6 5 4
inputFormat
The input is provided via standard input (stdin) and consists of three lines:
- The first line contains a single integer \(n\) representing the number of elements in the list. \(n\) can be zero.
- The second line contains \(n\) space-separated integers. If \(n = 0\), this line will be empty.
- The third line contains an integer \(k\), which denotes the number of largest elements to retrieve.
outputFormat
The output should be printed to standard output (stdout) as a single line containing the \(k\) largest elements in descending order, separated by a space. If there are no elements to output, print an empty line.
## sample6
3 1 5 2 4 6
3
6 5 4
</p>