Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Selected Reading
Program to find out the k-th smallest difference between all element pairs in an array in C++
Suppose we are given a list containing several integer numbers. We have to find out the difference between each pair of values in the array and find out the k-th smallest difference number. The index starts at 0 and the value k is given to us as input.
So, if the input is like numbers = {2, 6, 4, 8}, k = 2, then the output will be 2.
The differences between the pairs are −
(2, 6) = 4
(2, 4) = 2
(2, 8) = 6
(6, 4) = 2
(6, 8) = 2
(4, 8) = 4
If we sort the values, it becomes 2, 2, 2, 4, 4, 6. The 2-nd smallest value is 2. (Index starts from 0).
To solve this, we will follow these steps −
- increase k by 1
- sort the array input
- le := 0
- ri := last element of input - first item of input
- while le
- mid := (le + ri) / 2
- tmp := 0
- lp := 0
- for initialize i := 1, when i
- while input[i] - input[lp] > mid, do −
- lp := lp + 1
- tmp := tmp + i - lp
- ri := mid
- le := mid + 1
Example
Let us see the following implementation to get better understanding −
#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;
Output
2
Advertisements
