![]() |
VOOZH | about |
Given an array A of size N. In one operation, you can select any number from the array and reduce it to a divisor greater than 1. For example, you can reduce 16 to 2, 4, 8 or 16. You need to find the minimum range of the array by doing any number of operations on the array. You can do multiple operations on a single element as well. The range of the array is defined as the difference between the maximum element and minimum element of the array.
Examples:
Input: N=3 , A=[2 4 8]
Output: 0
Explanation: We can convert the array into [2, 2, 2]. So the difference between the maximum element and minimum element is zero.Input: N=3 ,A=[3 8 9]
Output:1
Explanation: We can convert the array into [3, 2, 3]. So the difference between the maximum element and minimum element is one.
Approach: We can solve this problem using the below idea
The first observation is that the duplicate elements does not add any thing to the result. for Example [2, 4, 8, 8] in this example if the first 8 is reduce to 2 likewise the other 8 can also be reduced to 2. The main aim of the problem is to minimize the difference between maximum and minimum element of the array. So in order to minimize the difference, we have two options one is to maximize the minimum element of the array or minimize the maximum element of the array. Lets concentrate on maximize the minimum element of the array. Consider an example of [2, 4, 8]. Listing out the factors ( > 1) of these numbers:
Indexes = [0, 1, 2]
2 = [2]
4 = [2, 4]
8 = [2, 4, 8]We will keep pick up the minimum element from all of the factors of a particular number and push them into a heap. And will keep track of maximum element in the maximum variable. We will pop the smallest element from the heap now difference the smallest element and maximum element that we have kept track of can be the answer. But if there is another factor for the element we have popped we push the factor into the heap again by doing so we can increase the minimum element of the array. We will continue doing the same procedure until the heap becomes empty. And will return minimum of the all those.
Steps to Solve this problem:
Below is the Implementation of the above approach:
1
Time Complexity: O(NlogN). Where N is the number of elements of the array
Auxiliary space: O(N * sqrt(N)), Where N is the number of elements of the array.