![]() |
VOOZH | about |
Given an array arr[] of length N ≥ 2. The task is to remove an element from the given array such that the GCD of the array after removing it is maximized.
Examples:
Input: arr[] = {12, 15, 18}
Output: 6
Remove 12: GCD(15, 18) = 3
Remove 15: GCD(12, 18) = 6
Remove 18: GCD(12, 15) = 3Input: arr[] = {14, 17, 28, 70}
Output: 14
Approach:
In this approach, we iterate through each element of the array and remove it to get the remaining array. We then calculate the GCD of the remaining array and keep track of the maximum GCD found so far. Finally, we return the maximum GCD.
14
Time Complexity: O(n^2 * log(max(a))), where n is the size of the array and max(a) is the maximum value in the array. This is because the function gcd has a time complexity of O(log(max(a))) and the function MaxGCD has two nested loops, each of which iterates n times.
Auxiliary Space: O(n^2) because the function MaxGCD creates a new array of size n-1 for each element of the input array, resulting in n^2 total elements in all created arrays.
Approach:
Below is the implementation of the above approach:
14
Time Complexity: O(N * log(M)) where M is the maximum element from the array.
Auxiliary Space: O(N)