Print Largest N Integers
EasyPractice library · +10 XPheapspriority queuestop-k
Given a list of N integers and an integer K, print the K largest integers from the list. The output should be sorted in ascending order.
Input
The first line contains two integers, N and K. The second line contains N space-separated integers.
Output
Print K space-separated integers, the K largest from the input list, sorted in ascending order. If there are fewer than K integers in the input, print all of them in ascending order.
Constraints
1 <= N <= 1000, 1 <= K <= N, -10^9 <= integer <= 10^9
Time limit 1 s (native code; slower languages get more)Memory 256 MB13 hidden tests
Example 1
Input
5 3 10 4 8 12 6
Output
8 10 12
The 3 largest elements are 8, 10, 12. Sorted, they are 8 10 12.
Example 2
Input
7 5 1 2 3 4 5 6 7
Output
3 4 5 6 7
The 5 largest elements are 3, 4, 5, 6, 7. Sorted, they are 3 4 5 6 7.
Hints
# Read the input from stdin and print the answer.
import sys
def main():
data = sys.stdin.read().split()
# your code here
main()
Example 1 input
5 3 10 4 8 12 6
Example 2 input
7 5 1 2 3 4 5 6 7