# Count pairs in an array that hold i*arr[i] > j*arr[j] in C++

C++Server Side ProgrammingProgramming

We are given an array of numbers. The goal is to find the pair of elements of array such that they hold the condition

If (i*arr[i] > j*arr[j]) then (arr[i],arr[j]) is a valid pair.

If the array is [ 5,4,3,2,1 ] then pairs will be [3,1] and [2,1].

Let us understand with examples.

Input − arr[] = [ 1,5,4,1,2,8,3 ]

Output − Count of pairs in an array that hold i*arr[i] > j*arr[j] are − 3

Explanation − Pairs are (5,1), (4,1), (8,3)

Input − arr[] = [ -1,-2,3,4,5,6 ]

Output − Count of pairs in an array that hold i*arr[i] > j*arr[j] are − 1

Explanation − Pair is (-1,-2)

## Approach used in the below program is as follows

We will traverse from 1 to N using for loop twice. For every i and arr[i] search for j and arr[j] such that condition i*arr[i]>j*arr[j] ( and i!=j). Increment count if condition is true.

• Take an array of integers.

• Function condition_pair(int arr[], int size) takes the array and its size and returns the count of pairs such that the condition is met.

• Take the initial count as 0.

• Traverse from i=1 to i <size-1

• Travers from j=i+1 to j<size.

• If ( i*arr[i] ) > ( j*arr[j] ) is true. Increment count.

• For each i and j calculate temp= (i*j)%(i+j).

• After the end of both iterations, count will have a total number of such pairs.

• Return count as result.

## Example

Live Demo

#include <iostream>
using namespace std;
int condition_pair(int arr[], int size){
int count = 0;
for (int i = 0; i < size - 1; i++){
for (int j = i + 1; j < size; j++){
if(i*arr[i] > j*arr[j]){
count++;
}
}
}
return count;
}
int main(){
int arr[] = { 2, 4, 1, 9, 6 };
int size = sizeof(arr) / sizeof(arr[0]);
cout<<"Count of pairs in an array that hold i*arr[i] > j*arr[j] are: "<<condition_pair(arr, size);
return 0;
}

## Output

If we run the above code it will generate the following output −

Count of pairs in an array that hold i*arr[i] > j*arr[j] are: 2
Updated on 02-Dec-2020 11:34:05