Sum of First K Elements
EasyPractice library · +10 XPheapspriority queuesk-selection
Given an array of N integers and an integer K, find the sum of the K smallest elements in the array. The elements can be positive, negative, or zero.
Input
The first line contains two integers, N and K, separated by a space. The second line contains N integers, the elements of the array, separated by spaces.
Output
Print a single integer, the sum of the K smallest elements.
Constraints
1 <= N <= 1000 1 <= K <= N -10^9 <= array element <= 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 2 6
Output
12
The 3 smallest elements are 2, 4, 6. Their sum is 12.
Example 2
Input
7 2 -5 1 0 -10 20 3 7
Output
-15
The 2 smallest elements are -10, -5. Their sum is -15.
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 2 6
Example 2 input
7 2 -5 1 0 -10 20 3 7