HackerRank 'Max Min' Solution

by Srikant Padala on April 14, 2016, 7:22 am


Explanation


  • Sort the Array
  • Find the unfairness of K elements groups starting from 0 upto N-K
  • Get the minimum of all these unfairnesses

Max Min Problem Statement

Video

#include <cmath>
#include <cstdio>
#include <vector>
#include <iostream>
#include <algorithm>
#include <climits>
using namespace std;

int main() {
    int N, K, unfairness = INT_MAX, temp;
    cin >> N >> K;
    vector<int> list(N);
    for (int i=0; i<N; i++)
        cin >> list[i];
    
    /** Write the solution code here. Compute the result, store in  the variable unfairness --
    and output it**/
    sort(list.begin(), list.end());
    for(int i=0; i <= N-K; i++) {
        temp = list[i+K-1] - list[i];
        if(temp < unfairness) unfairness = temp;
    }
    cout << unfairness << "
";
    return 0;
}

Coming Soon.