Sort the array in non-decreasing order. Now notice that, the smallest interval that starts at ai and contains at least K integers is [ai , ai+k-1]. Therefore, you can find the size of the smallest interval by running a loop over the entire sorted array.

C++ code:

#include <bits/stdc++.h>

#define NMAX 2147483647

using namespace std;
 
int n,t,k,ar[100005]; 
 
int main () {

    cin >> n >> k;

    for(int i = 1; i <= n; i++) {
        cin >> ar[i];
    }
 
    sort(ar+1, ar+n+1);

    int ans = NMAX;

    for(int i = 1; ; i++) {
        if(i+k-1 > n) break; //all K-sized intervals found

        ans = min(ans, ar[i+k-1] - ar[i]);
    }

    cout << ans << endl;
 
    return 0;
}

Contributors

Statistics

85% Solution Ratio
ArpancseEarliest, May '17
nusuBotFastest, 0.0s
ArpancseLightest, 524 kB
Rafi9998Shortest, 210B
Toph uses cookies. By continuing you agree to our Cookie Policy.