CODBLND3 - Editorial

PROBLEM LINK:

Practice

Author: Toshani Rungta
Editorialist: Toshani Rungta

DIFFICULTY:

EASY

SOLUTION:

This problem can be considered as a simple sorting and binary search algorithm question. Find the distances between each pair of numbers which is the absolute difference between them. Sort these in ascending order and print the distance at the index k-1.

CODE:

#include "bits/stdc++.h"
using namespace std;

int32_t main () {
    int n, k;
    scanf("%d%d", &n, &k);
    vector <int> positions(n), distances;
    for (int i = 0; i < n; i++) {
        scanf("%d", &positions[i]);
    }
    for (int i = 0; i < n; i++) {
        for (int j = i + 1; j < n; j++) {
            distances.push_back(abs(positions[i] - positions[j]));
        }
    }
    sort(distances.begin(), distances.end());
    printf("%d\n", distances[k-1]);
}