In this Leetcode Chocolates and Boxes, problem-solution Alice has N boxes, and each box has a certain non-zero number of chocolates. These boxes are numbered from 1 to N.

Alice is planning to go to wonderland. She wants to carry exactly K number of chocolates and she can carry only 2 boxes. So she wants to know the number of ways in which she can select 2 boxes such that the total number of chocolates in them is K.


HackerEarth Chocolates and Boxes problem solution


HackerEarth Chocolates and Boxes problem solution.

int main()
{
    int t;
    cin>>t;
    while(t--)
    {
        int n;
        cin>>n;
        int arr[300000];
        rep(i,n)
            cin>>arr[i];
        int k;
        cin>>k;
        int mul[300000];
        for(int i=0;i<k;i++)
            mul[i]=0;
        long long int ways=0;
        for(int i=0;i<n;i++)
        {
            if(arr[i]<k)
                mul[arr[i]%k]++;
        }
        for(int i=1;i<=(k/2);i++)
        {
            if(2*i == k && mul[i]>=2)
                ways+=(mul[i]*(mul[i]-1)/2);
            else
                ways+=mul[i]*mul[k-i];
        }
        cout<<ways<<endl;
    }
    return 0;
}