This is a HackerRank Problem ,I have written my code in c++ , but I am not getting correct output:
Here's the problem:
There is a large pile of socks that must be paired by color. Given an array of integers representing the color of each sock, determine how many pairs of socks with matching colors there are.
n = 10
arr = [1,1,3,1,2,1,3,3,3,3]
Output: 4
Explation: There is two pair of color 1 and two of color 3. There are two odd socks left, one of each color. The number of pairs is 4.
#include <bits/stdc++.h>
using namespace std;
int main()
{
int n;
cin>>n;
int arr[n];
for(int i=0;i<n;i++)
cin>>arr[i];
sort(arr,arr+n);
int sum=1,count=0;
for(int i=0;i<n-1;i++)
{
if(arr[i]==arr[i+1])
sum += 1;
else
{
count += sum/2;
sum = 1;
}
}
cout<<count;
}
My output : 2.
Correct output : 4