Home >Backend Development >C++ >Write a program in C++ to find the kth smallest difference between all pairs of elements in an array
Suppose we have a list containing multiple integers. We have to find the difference between each pair of values in the array and find the kth smallest number of differences. The index starts from 0 and the value k is given to us as input.
So if the input is something like numbers = {2, 6, 4, 8}, k = 2, then the output will be 2.
The difference between the two pairs is -
(2, 6) = 4
(2, 4) = 2
(2, 8 ) = 6(6, 4) = 2
(6, 8) = 2
(4, 8) = 4
If we Sorting the values, it becomes 2, 2, 2, 4, 4, 6. The second minimum value is 2. (indexed from 0).
To solve this problem, we will follow the following steps-
#include<bits/stdc++.h> using namespace std; int solve(vector<int>& input, int k) { k++; sort(input.begin(), input.end()); int le = 0; int ri = input.back() - input[0]; while (le < ri) { int mid = (le + ri) / 2; long long tmp = 0; int lp = 0; for (int i = 1; i < input.size(); i++) { while (input[i] - input[lp] > mid) lp++; tmp += i - lp; } if (tmp >= k) ri = mid; else le = mid + 1; } return le; } int main() { vector<int> numbers = {2, 6, 4, 8}; cout<< solve(numbers, 2) <<endl; return 0; }Input
vector<int> numbers = {2, 6, 4, 8}; cout<< solve(numbers, 2) <<endl;
2
The above is the detailed content of Write a program in C++ to find the kth smallest difference between all pairs of elements in an array. For more information, please follow other related articles on the PHP Chinese website!