Problem solving with programming: Number of matching pairs
Given an array containing values in the range [-10,10], find out how many number of matching pairs are possible?
A pair of numbers is said to be matching if one value is negative of the other (two zeros are also considered matching pair).
Consider the following examples.
[-6, 0, 1, 6, 0, -1] contains 3 matching pairs. Indices are (0,3), (1,4), (2,5)
[0, 0, 0, -5 ,3, 5] contains 4 matching pairs. Indices are (0,1), (0,2), (1,2), (3,5)
Now, the number of matching pairs is the sum of Count(-x) * Count(x) for 1<=x<=10
The number of possible pairs for n zeros is n*(n-1)/2
Given an array containing values in the range [-10,10], find out how many number of matching pairs are possible?
A pair of numbers is said to be matching if one value is negative of the other (two zeros are also considered matching pair).
Consider the following examples.
[-6, 0, 1, 6, 0, -1] contains 3 matching pairs. Indices are (0,3), (1,4), (2,5)
[0, 0, 0, -5 ,3, 5] contains 4 matching pairs. Indices are (0,1), (0,2), (1,2), (3,5)
Now, the number of matching pairs is the sum of Count(-x) * Count(x) for 1<=x<=10
The number of possible pairs for n zeros is n*(n-1)/2
Read full article from Problem solving with programming: Number of matching pairscin >> n;vector<long long> input(21);int i,j;for( i = 0; i < n; i++ ){int r;cin >> r;input[ r+10 ]++;}long long result = 0;i = 0;j = 20;while ( i < j ){result += input[i]*input[j];i++;j--;}result += input[10]*(input[10]-1)/2;cout << result << endl;