Count pairs from an array having product of their sum and difference equal to 1 | C ++ program for the above approach ; Function to count the desired number of pairs ; Initialize oneCount ; Initialize the desiredPair ; Traverse the given array ; If 1 is encountered ; If 0 is encountered ; Update count of pairs ; Return the final count ; Driver Code ; Given array arr [ ] ; Function Call
#include <bits/stdc++.h> NEW_LINE using namespace std ; int countPairs ( int arr [ ] , int n ) { int oneCount = 0 ; int desiredPair = 0 ; for ( int i = 0 ; i < n ; i ++ ) { if ( arr [ i ] == 1 ) { oneCount ++ ; } if ( arr [ i ] == 0 ) { desiredPair += oneCount ; } } return desiredPair ; } int main ( ) { int arr [ ] = { 3 , 1 , 1 , 0 } ; int N = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; cout << countPairs ( arr , N ) ; return 0 ; }