I solved it using top down approach .

long long int dp[501][501]={-1};

long long int solve(vector < int > &a, int i , int rem)

{

//If no elements are remaining in array or you can`t add any elements further return 0;

if(i<0 || rem<=0)

{

return 0;

}

// this case handles when you are at first element .It should return zero because you can`t take any element before it to pair with .

if(i==0)

{

return 0;

}

else if(dp[i][rem]!=-1)

{

return dp[i][rem];

}

else

{

dp[i][rem]=0;

// trying every pair (i,j) where j= i-1 to 0 and recursing with j-1 to 0 .

for(int j=i-1;j>=0;j–)

{

dp[i][rem]=max(dp[i][rem],__gcd(a[i],a[j])+solve(a,j-1,rem-2));

}

dp[i][rem]=max(dp[i][rem],solve(a,i-1,rem)); // This is handling case when you are ignoring element at ith index .

return dp[i][rem];

}

}

Here rem is denoting number of elements that can still be inserted if we are at index i .

So initially we are at index n-1 (0 based indexing ) and elements that can be inserted are 2 * B .

so ans will be solve(a,n-1,2 * B);