Maximum possible GCD after replacing at most one element in the given array | C ++ implementation of the approach ; Function to return the maximum possible gcd after replacing a single element ; Prefix and Suffix arrays ; Single state dynamic programming relation for storing gcd of first i elements from the left in Prefix [ i ] ; Initializing Suffix array ; Single state dynamic programming relation for storing gcd of all the elements having index greater than or equal to i in Suffix [ i ] ; If first or last element of the array has to be replaced ; If any other element is replaced ; Return the maximized gcd ; Driver code
#include <bits/stdc++.h> NEW_LINE using namespace std ; int MaxGCD ( int a [ ] , int n ) { int Prefix [ n + 2 ] ; int Suffix [ n + 2 ] ; Prefix [ 1 ] = a [ 0 ] ; for ( int i = 2 ; i <= n ; i += 1 ) { Prefix [ i ] = __gcd ( Prefix [ i - 1 ] , a [ i - 1 ] ) ; } Suffix [ n ] = a [ n - 1 ] ; for ( int i = n - 1 ; i >= 1 ; i -= 1 ) { Suffix [ i ] = __gcd ( Suffix [ i + 1 ] , a [ i - 1 ] ) ; } int ans = max ( Suffix [ 2 ] , Prefix [ n - 1 ] ) ; for ( int i = 2 ; i < n ; i += 1 ) { ans = max ( ans , __gcd ( Prefix [ i - 1 ] , Suffix [ i + 1 ] ) ) ; } return ans ; } int main ( ) { int a [ ] = { 6 , 7 , 8 } ; int n = sizeof ( a ) / sizeof ( a [ 0 ] ) ; cout << MaxGCD ( a , n ) ; return 0 ; }