Question Name:ADD-SUBTRACT

#include <bits/stdc++.h>
 
using namespace std;
 
int main(){
    int t,n,k,cost,min1,max1;
    int a[100], b[100];
    cin>>t;
    while(t--){
        cost = min1 = INT_MAX;
        max1 = INT_MIN;
        cin>>n>>k;
        for(int i = 0; i < n; i++){
            cin>>a[i];
            min1 = min(min1,a[i]);
            max1 = max(max1,a[i]);
        }
        for(int i = min1; i <= max1; i++){
          int temp = 0;
          for(int j = 0; j < n; j++){
              if(a[j] >= i) b[j] = (a[j] - i)*5;
              else b[j] = (i - a[j])*3;
          }
          sort(b, b+n);
          for(int j = 0; j < k; j++){
            temp += b[j];  
          }
          cost = min(cost, temp);
        }
        cout<<cost<<endl;
    }
    return 0;
}

Problem Description

Chandan is back with his array to blow your mind. As usual Chandan has an array consisting of N integers .He allows you to perform 2 kinds of operation on his array.

Type 1 : Increment any integer of the array by 1.

Type 2 : Decrement any integer of the array by 1.

You can perform these operation as many times as you want on his array.

Each operation of Type 1 costs 3 while each operation of Type 2 costs 5.

Now Chandan wants to have K equal elements in his array.So he asks you to tell him the minimum cost required in obtaining K equal elements in his array.

Input:

The first line contains T indicating test cases.Second line contains 2 integers N indicating the number of elements in his array and K.

Third line contains N space separated integers denoting Chandan array.

Output:

The minimum cost required to get K equal elements.

Constraints :

1 <= T <= 100

1 <= K <= N <=100

1 <= A[i] <=100

  • Test Case 1

    Input (stdin)

    1
    5 3
    9 4 9 7 4
    

    Expected Output

    6
  • Test Case 2

    Input (stdin)

    1
    5 5
    9 4 9 7 2
    

    Expected Output

    42
Ads Blocker Image Powered by Code Help Pro

Ads Blocker Detected!!!

We have detected that you are using extensions to block ads. Please support us by disabling these ads blocker.

Powered By
100% Free SEO Tools - Tool Kits PRO