ronith
5/29/2018 - 8:20 PM

Minimum swaps required to bring all elements less than or equal to k together

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

int check(int *a, int n, int k){
    int c = 0;

    for (int i = 0;i<n;i++)
        if (a[i] <= k)
            c += 1;
    return c;
}

int main(){
    int n;
    cout << "No.of elements \n";
    cin >> n;
    int a[n];
    cout << "Enter the elements \n";
    for (int i = 0;i<n;i++)
        cin >> a[i];
    cout << "Enter k:";
    int k;
    cin >> k;
    int total = check(a,n,k);

    int c = 0;
    for(int i = 0;i< total; i++){
        if (a[i] <= k)
            c++;
    }

    for(int i = 1; i <n-k+1;i++){
        int b[total];
        memcpy(b, a+i, total*sizeof(int));

        int d = check(b,total,k);
        if (c < d)
            c = d;
    }
    cout << total - c;
}