VOOZH about

URL: https://www.geeksforgeeks.org/dsa/remove-an-element-to-maximize-the-gcd-of-the-given-array/

⇱ Remove an element to maximize the GCD of the given array - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Remove an element to maximize the GCD of the given array

Last Updated : 12 Jul, 2025

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:
Remove 12: GCD(15, 18) = 3 
Remove 15: GCD(12, 18) = 6
Remove 18: GCD(12, 15) = 3

Input: 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.

  • Define a function gcd to calculate the greatest common divisor of two integers using the Euclidean algorithm.
  • Define a function MaxGCD which takes an array a and its length n as input and returns the maximum possible GCD after removing one element from the array.
  • Initialize a variable ans to 0.
  • Iterate over the array and remove each element in turn. To do this, create a temporary array temp of size n-1, and copy all elements from a except the current element to temp.
  • Calculate the GCD of the elements in temp using the gcd function. Set this value to a variable res.
  • Update the value of ans to be the maximum of its current value and res.
  • Return the value of ans as the final answer.

Output
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:

  • Idea is to find the GCD value of all the sub-sequences of length (N - 1) and removing the element which is not present in the sub-sequence with that GCD. The maximum GCD found would be the answer.
  • To find the GCD of the sub-sequences optimally, maintain a prefixGCD[] and a suffixGCD[] array using single state dynamic programming.
  • The maximum value of GCD(prefixGCD[i - 1], suffixGCD[i + 1]) is the required answer.

Below is the implementation of the above approach:  


Output
14

Time Complexity: O(N * log(M)) where M is the maximum element from the array.

Auxiliary Space: O(N)

Comment