Count all distinct pairs with difference equal to k in C++

C++Server Side ProgrammingProgramming

In this tutorial, we will be discussing a program to find the distinct pairs with difference equal to k.

For this we will be provided with an integer array and the value k. Our task is to count all the distinct pairs that have the difference as k.

Example

 Live Demo

#include<iostream>
using namespace std;
int count_diffK(int arr[], int n, int k) {
   int count = 0;
   //picking elements one by one
   for (int i = 0; i < n; i++) {
      for (int j = i+1; j < n; j++)
         if (arr[i] - arr[j] == k || arr[j] - arr[i] == k )
            count++;
   }
   return count;
}
int main(){
   int arr[] = {1, 5, 3, 4, 2};
   int n = sizeof(arr)/sizeof(arr[0]);
   int k = 3;
   cout << "Count of pairs with given diff is" << count_diffK(arr, n, k);
   return 0;
}

Output

Count of pairs with given diff is 2
raja
Published on 05-Feb-2020 12:10:41
Advertisements