Wednesday, July 15, 2020

Question:

Coders here is a simple task for you, you have given an array of size N and an integer M. 
 
Your task is to calculate the difference between maximum sum and minimum sum of N-M elements of the given array. 
 
Constraints: 
 
1<=t<=10 1<=n<=1000 1<=a[i]<=1000 
 
Input: 
 
First-line contains an integer T denoting the number of test cases. The first line of every test case contains two integer N and M. Next line contains N space-separated integers denoting the elements of an array 
 
Output: 
 
For every test case print your answer in a new line 
 
SAMPLE INPUT  
 
1
5 1
1 2 3 4 5 
 
SAMPLE OUTPUT  
 
4 
 
Explanation 
 
M is 1 and N is 5 so you have to calculate maximum and minimum sum using (5-1 =) 4 elements. The maximum sum using the 4 elements would be (2+3+4+5=)14. The minimum sum using the 4 elements would be (1+2+3+4=)10. The difference will be 14-10=4. 
 
 Answer:

#include <stdio.h>

int main()
{
   int t; 
    scanf("%d",&t); 
    while(t--)
    { 
        int n,m; 
        scanf("%d %d",&n,&m); 
        int arr[n]; 
        for(int i=0;i<n;i++)
       { 
            scanf("%d",&arr[i]); 
        } 

        for(int k=0;k<n;k++)
       { 
            int smallest=k; 
            for(int l=k+1;l<n;l++)
           { 
                if(arr[smallest]>arr[l]){ 
                    smallest=l; 
             } 
        } 
            int temp=arr[k]; 
            arr[k]=arr[smallest]; 
            arr[smallest]=temp; 
      } 

        long max=0; 
        for(int j=m;j<n;j++)
       { 
            max+=arr[j]; 
        } 
        
        long min=0; 
        for(int j=0;j<n-m;j++)
       { 
            min+=arr[j]; 
        } 
        printf("%d\n",max-min); 
    } 
    return 0;
}


Output:
1                                                                                                          
5 1                                                                                                        
1 2 3 4 5                                                                                                  

No comments:

Post a Comment