Question : -

Divison 1

Division 2

Now first we think the basic approach and how to do that?

Now gcd of two elements is always min or equal to gcd of single element –

see gcd(4,7) < gcd(4) OR gcd(4,8) <= gcd(4) OR gcd(8)

Now most of us think that we can take max value on one side and take gcd of all values ,

ie. a= {1,2,3,4,5} so max sum will be gcd(5) + gcd(1,2,3,4) = 6

But this is wrong in many cases , lets take an example a = {10,14,15}

Now according to our approach answer will be gcd(15) + gcd(10,14) = 15+2=17 , but the correct answer is 19 how —> gcd(14)+gcd(10,15) = 14 + 5 = 19.

so for 20 marks we can try for each element and find the max answer,

Steps : -

- Convert given array to set, so the only unique value is present
- if( the set size is 1 that means it contains only same value)

output will be twice of element.

example : ={2,2,2,2,2,2} set = {2} answer = 4 [ gcd(2) + gcd(2,2,2,2,2) ]

else

try for each element

example = {2,4,2,6,4,5,8} , set = {2,4,5,6,8}

2+gcd(4,5,6,8) = 2 + 1 = 3

4+gcd(2,5,6,8) = 4 + 1 = 5

5+gcd(2,4,6,8) = 5 + 2 = 7

6+gcd(2,4,5,8) = 6 + 1 = 7

8+gcd(2,4,5,6) = 8 + 1 = 9

So max answer is**9**, But the complexity of this approach is O(n^2).

See Solution : Brute Force ( O(N^2) solution)

But how to do that with O(N) complexity.

We have to calculate GCD of all element except current element (OR excluding the i’th element from an array(set))

We use concept of prefix and suffix array and we can use concept of this article also

(after my submission I found this)

see - Geeks-for-geeks

Now we can do this in O(N) complexity.

See : O(N) Solution [ prefix and suffix approach]

if u like this please upvote and if u want further explanation, I will be happy.