You are given an array of integers. Find the sum of first K smallest numbers.
K Sum Contest Problem
Input :
First line of input contains number of testcases T. The 1st line of each testcase contains a two integers N denoting the number of elements in the array A and K. The 2nd line of each testcase, contains N space separated integers denoting the elements of the array A.
Output :
For each testcase you need to print the sum of K smallest numbers.
Constraints :
1 <= T <= 50
1 <= N <= 105
1 <= K <= N
0 <= A[i] <= 106
Example :
Input :
1
6 4
1 3 4 1 3 8
Output :
8
Explaination :
Testcase1: Sum of first 4 smallest numbers is 1+1+3+3 = 8
Solution:
import java.util.*;
import java.lang.*;
import java.io.*;
public class KSum {
static class FastReader{
BufferedReader br;
StringTokenizer st;
public FastReader(){
br = new BufferedReader(new InputStreamReader(System.in));
}
String next(){
while (st == null || !st.hasMoreElements()){
try {
st = new StringTokenizer(br.readLine());
}catch (IOException e) {
e.printStackTrace();
}
}
return st.nextToken();
}
int nextInt(){
return Integer.parseInt(next());
}
String nextLine(){
String str = "";
try {
str = br.readLine();
} catch (IOException e) {
e.printStackTrace();
}
return str;
}
}
public static void main(String[] args) {
FastReader fr = new FastReader();
int t = fr.nextInt();
while (t-->0){
int n = fr.nextInt();
int k = fr.nextInt();
int[] arr = new int[n];
for (int i = 0; i < n; i++) {
arr[i] = fr.nextInt();
}
Arrays.sort(arr);
long sum = 0;
for (int i = 0; i < k; i++) {
sum+=arr[i];
}
System.out.println(sum);
}
}
}
#include <bits/stdc++. h>
using namespace std;
int main() {
//code
int T;
cin>>T;
while(T--){
int N,K;
cin>>N>>K;
int arr[N];
for(int i=0; i<N; i++){
cin>>arr[i];
}
sort(arr,arr + N);
long long sum = 0;
for(int i=0; i<K ;i++){
sum += arr[i];
}
cout<<sum<<endl;
}
return 0;
}
Happy Learning – If you require any further information, feel free to contact me.