BARCLAYS INTERN OA || HELP NEEDED

I got this question , question was quite straight forward but still don’t know got wrong answer many time.
attaching both questions as well as my code=>

My code
 int solve(int N, int y, vector<int> arr) {
        // code here
        int mini = *min_element(arr.begin(), arr.end());
        int add = y-mini;
        
        for(int i=0;i<N;i++)
        {
            arr[i] = arr[i]+add;
        }
        
        int ans=0;
        for(int i=0;i<N;i++)
        {
            if(arr[i]==y)
            {
                ans++;
            }
        }
        return ans;
    }

Constraints:
2<=n<=10^5
-10^9<=y<=10^9
0<=arr[i]<=10^9

Please give your code anyone

Let array A1 = [a1, a2, a3, … , an]
Let us add X to it.
Then array A2 = [a1+X, a2+X, a3+X, … , an+X]

Now we will notice that since all the number are getting either incremented or decremented by the same value, the max frequency in both arrays DOES NOT CHANGE.

Proof

Let us say that K of them reach the target value y after some operations.
Formally,
Aa + X = y
Ab + X = y
Ac + X = y


Ak + X = y

So, for all these equations to be valid,
Aa = Ab = Ac = … = Ak

So, our final answer depends on maximum frequency of array.

Example

A1 = [1, 5, 2, 3, 2]
X = 5;
Here element 5 has the highest frequency of 2.

then
A2 = [6, 10, 7, 8, 7]
Here also element 7 has the highest frequency of 2.

So the finaly answer will be 2. Irrespective of any value of y.

NOTE :- Max frequency before and after any number of operations never changes.

So now we will take the required X, and perform the operation to get the target value y.

Finally

So accordingly, the final answer for a given array irrespective of the value of y, only depends on max frequency of the array.
So just find the max frequency and return the ans.

You can check it out further by going through some more test cases.
PS:- This code is quite easy. You can do it yourself.

You’re absolutely right !!

1 Like