![]() |
VOOZH | about |
Given an array arr[] of size N, the task is to minimize the number of distinct elements in the array after performing the following operation once:
Examples:
Input: N = 5, arr[] = {5, 10, 20, 35, 15}
Output: 1
Explanation: Lets take X = 5. On replacing each element
as mentioned above we get arr = {0, 0, 0, 0, 0}.
Now this array has only one distinct element (0).Input: N = 4, arr[] = {1, 4, 8}
Output: 2
Approach: To solve the problem follow the below observation:
The answer would be at - most 2.
This would be the case when we choose X = 2. The final array will contain only either 0 (for even numbers) or 1 (for odd numbers).
So, now the task is to check for the condition when the answer would be 1.
We want to find X, such that A[1] % X = A[2] % X, A[2] % X = A[3] % X, and so on for the whole array.
Therefore, (A[1] - A[2]) % X = 0 and (A[2] - A[3]) % X = 0 and so on for the whole array.
Therefore, we need to find an X, such that all the consecutive differences are divisible by it.
So, the following steps can be followed to solve the problem:
Below is the implementation of the above approach.
1
Time Complexity: O(N * log(M)) where M is the maximum value of the array
Auxiliary Space: O(1)