
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Count All Distinct Pairs with Difference Equal to K in C++
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
#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
Advertisements