K Sum - Solution

CoderIndeed
1 minute read
0

Problem : K Sum 

You are given an array of integers. Find the sum of first K smallest numbers.

Hint

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:

 #include <bits/stdc++.h>
using namespace std;

int main() {
    //code
    int T;
    cin>>T;
    
    while(T--){
        int N, K;
        cin>>N>>K;
        int array[N];
        
        for(int i=0; i<N; i++){
            cin>>array[i];
        }
        
        sort(array, array+N);
        
        long long sum = 0;
        for(int i=0; i<K; i++){
            sum+=array[i];
        }
        
        cout<<sum<<endl;
    }
    return 0;
}

Post a Comment

0Comments

Post a Comment (0)

#buttons=(Accept !) #days=(20)

Our website uses cookies to enhance your experience. Check Now
Accept !