Insights
-
The Maximum Number of operations) would be
n
to make every number equal.
i.e if we modulo every a_i with 1 -
When we take modulo with a positive number M,
we can get number from range [0, min( a_i, M))
i.e if M > a_i => a_i \% M = a_i \ \ \ \ for eg: 1 % 2 = 1 -
You cannot get a bigger number from a smaller number after doing modulo operation with a positive number M
-
So the best we can do is try to make every number equal to the smallest number.
-
If we can’t make every number after operation equal to the smallest number; then we would have to do n operation.
Reason: We need to find a number smaller than the smallest number, so in-turn we would have to do operations on the smallest number and all the numbers greater than the smallest number.
Algorithm
- Find the minimum element from the array
- Loop through the array.
- if arr[i] == min_element continue (we don’t need to perform operations on this element since its already the smallest element)
- Check if you can get the min_element from the current element
if (arr[i] % (arr[i] - min_element)) == min_element
Code (function Snippet)
int ModEquality(vector<int> &arr)
{
int n = arr.size();
int num = *min_element(arr.begin(), arr.end());
int count = 0;
for (int el : arr)
{
if (el == num)
continue;
else
{
int modular = el - num;
if (el % modular != num)
return n;
else
count++;
}
}
return count;
}