I'm trying to write a function in CPP to find how many pairs in array.
I got Segmentation Fault on this case --> [10, 20, 20, 10, 10, 30, 50, 10, 20]
The Algorithm I'm trying to use is find out how many time the Number repeated and divided by 2.
Input --> [10, 20, 20, 10, 10, 30, 50, 10, 20]
out put --> 3
Explanation :
There is 4 of items[10] --> 4/2 = 2.
there is 3 items[20] --> 3/2 = 1 Note get rid of any fraction
Here is my code :-
int sockMerchant(int n, vector<int> ar) {
int pairs = 0;
int arRange = 0;
for(int i = 0; i < n; i++)
{
if(ar[i] > ar[arRange])
arRange = ar[i];
}
arRange += 1;
int freq[arRange] = {0};
for(int i = 0; i < n; i++)
freq[ar[i]]++;
for(int i = 0; i <= arRange; i++)
{
int count = 0;
if(freq[i] > 1)
count = freq[i] / 2;
pairs = pairs + count;
}
return pairs;
}