Cricket Balls

Daksh has 'N' boxes of cricket balls and each box has a certain number of cricket balls (non-zero) in it. The boxes are numbered from 1 to N.

Now, Daksh has to go for practice to the cricket ground to compete in the upcoming fest URJA. Daksh wants to carry exactly K number of cricket balls to the ground and he can carry only 2 boxes. Can you tell him the number of ways in which he can select 2 boxes such that the total number of cricket balls in them is K?

Example:

Input:  n = 5, a = [1,2,3,4,3], sum = 6
Output: 2

Approach

C++

#include <bits/stdc++.h>
using namespace std;

long long cricketBalls(long long nlong long a[], long long sum)
{
    map<long longlong longmp;
    for (long long i = 0i < ni++)
        mp[a[i]]++;
    set<long longst;
    for (long long i = 0i < ni++)
        st.insert(a[i]);
    long long ans = 0;
    for (auto it = st.begin(); it != st.end(); it++)
    {
        long long x = *ity = sum - *it;
        if (mp[x] > 0 && mp[y] > 0)
        {
            if (x == y)
            {
                long long p = mp[x];
                ans += p * (p - 1) / 2;
            }
            else
            {
                long long p = mp[x]q = mp[y];
                ans += p * q;
            }
            mp[x] = 0;
            mp[y] = 0;
        }
    }
    return ans;
}
int main()
{

    long long n = 5;

    long long a[n] = {12343};

    long long sum = 6;

    cout << cricketBalls(nasum<< "\n";

    return 0;
}


No comments:

Post a Comment