![]() |
VOOZH | about |
Given an array arr[] of n elements. In one operation you can pick two indices i and j, such that arr[i] ≥ arr[j] and replace the value of arr[i] with (arr[i] - arr[j]), the task is to minimize the values of the array after performing any number of such operations.
Examples:
Input: n = 3, arr[] = {3, 2, 4}
Output: 1
Explanation:
- 1st Operation: We can pick 4 & 3, subtract 4-3 => {3, 2, 1}
- 2nd Operation: We can pick 3 & 2, subtract 3-2 => {1, 2, 1}
- 3rd Operation: We can pick 1 & 2, subtract 2-1 => {1, 1, 1}
- 4th Operation: We can pick 1 & 1, subtract 1-1 => {1, 0, 1}
- 5th Operation: We can pick 1 & 1, subtract 1-1 => {0, 0, 1}
After this, no operation can be performed, so the maximum no left in the array is 1, so the answer is 1.
Input: n = 2, arr[] = {2, 4}
Output: 2
Explanation:
- 1st Operation : We can pick 4 & 2, subtract 4-2 => {2, 2}
- 2nd Operation : We can pick 2 & 2, subtract 2-2 => {0, 2}
After this, no operation can be performed, so the maximum no left in the array is 2, so the answer is 2.
Approach:
Intuition behind this approach is to use sorting in ascending order to bring the closest elements together. And by iterating over the sorted array, we calculate the difference between adjacent elements to find the minimum difference. then minimum difference between adjacent elements gives the minimum value after performing the operations.
To do this, we can use the following steps:
Below is the implementation of the above approach:
1
Time Complexity: O(N*logN)
Auxiliary Space: O(1)
Approach: This can be solved with the following idea:
This problem can be solved using Heap Data Structure.
Below are the steps involved in the implementation of the code:
Below is the implementation of the above approach:
1
Time Complexity: O(N*logN)
Auxiliary Space: O(N)