Program to find maximize score after n operations in Python


Suppose we have an array called nums, whose size is 2*n. We have to perform n operations on this array. In the ith operation (1-indexed), we will do the following:

  • Select two elements, x and y.

  • Get a score of i*gcd(x, y).

  • Remove x and y from the array nums.

We have to find the maximum score we can get after performing n operations.

So, if the input is like nums = [6,2,1,5,4,3], then the output will be 14 because the optimal choices are (1 * gcd(1, 5)) + (2 * gcd(2, 4)) + (3 * gcd(3, 6)) = 1 + 4 + 9 = 14

To solve this, we will follow these steps −

  • n := size of nums

  • dp := an array of size (2^n) and fill with -1

  • Define a function dfs() . This will take mask, t

  • if mask is same as (2^n - 1), then

    • return 0

  • if dp[mask] is not same as -1, then

    • return dp[mask]

  • ma := 0

  • for i in range 0 to n, do

    • if 2^i AND mask is non-zero, then

      • go for next iteration

    • for j in range i + 1 to n - 1, do

      • if 2^j AND mask is non-zero, then

        • go for next iteration

      • next := dfs(mask OR 2^i OR 2^j, t+1) + gcd(nums[i], nums[j])*t

      • ma := maximum of next and ma

  • dp[mask] := ma

  • return dp[mask]

  • From the main method, return dfs(0, 1)

Example

Let us see the following implementation to get better understanding

from math import gcd
def solve(nums):
   n = len(nums)
   dp = [-1] * (1 << n)

   def dfs(mask, t):
      if mask == (1 << n) - 1:
         return 0
      if dp[mask] != -1:
         return dp[mask]
      ma = 0
      for i in range(n):
         if (1 << i) & mask:
            continue
         for j in range(i + 1, n):
            if (1 << j) & mask:
               continue
            next = dfs(mask | (1 << i) | (1 << j), t + 1) + gcd(nums[i], nums[j]) * t
            ma = max(next, ma)
      dp[mask] = ma
      return dp[mask]

   return dfs(0, 1)

nums = [6,2,1,5,4,3]
print(solve(nums))

Input

[6,2,1,5,4,3]

Output

14

Updated on: 08-Oct-2021

426 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements