Count pairs ( i , j ) from an array such that i < j and arr [ j ] | C ++ program for the above approach ; Function to count the number of pairs ( i , j ) such that i < j and arr [ i ] - arr [ j ] = X * ( j - i ) ; Stores the count of all such pairs that satisfies the condition . ; Stores count of distinct values of arr [ i ] - x * i ; Iterate over the Map ; Increase count of pairs ; Print the count of such pairs ; Driver Code
#include <bits/stdc++.h> NEW_LINE using namespace std ; void countPairs ( int arr [ ] , int n , int x ) { int count = 0 ; map < int , int > mp ; for ( int i = 0 ; i < n ; i ++ ) { mp [ arr [ i ] - x * i ] ++ ; } for ( auto x : mp ) { int n = x . second ; count += ( n * ( n - 1 ) ) / 2 ; } cout << count ; } int main ( ) { int n = 6 , x = 3 ; int arr [ ] = { 5 , 4 , 8 , 11 , 13 , 16 } ; countPairs ( arr , n , x ) ; return 0 ; }