Home >Backend Development >C++ >Write a program in C++ to find the kth smallest difference between all pairs of elements in an array

Write a program in C++ to find the kth smallest difference between all pairs of elements in an array

WBOY
WBOYforward
2023-09-05 17:25:06777browse

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-

  • Increase k by 1
  • Sort the array input
  • le: = 0
  • ri := The last element of the input - The first item of the input
  • while le
  • mid := (le ri) / 2
  • tmp := 0
  • lp := 0
  • is used to initialize i := 1, when i
  • while input[i] - input[lp] > mid, execute −
    • lp := lp 1
  • tmp := tmp i - lp
  • If tmp >= k, then -
    • ri := mid
  • ##otherwise
    • le := mid 1
  • Return le
  • Example

    Let us look at the following implementation to understand better -

    #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

    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!

  • Statement:
    This article is reproduced at:tutorialspoint.com. If there is any infringement, please contact admin@php.cn delete