Skip to content

1799. Maximize Score After N Operations

Difficulty Topics

Description

You are given nums, an array of positive integers of size 2 * n. You must perform n operations on this array.

In the ith operation (1-indexed), you will:

  • Choose two elements, x and y.
  • Receive a score of i * gcd(x, y).
  • Remove x and y from nums.

Return the maximum score you can receive after performing n operations.

The function gcd(x, y) is the greatest common divisor of x and y.

 

Example 1:

Input: nums = [1,2]
Output: 1
Explanation: The optimal choice of operations is:
(1 * gcd(1, 2)) = 1

Example 2:

Input: nums = [3,4,6,8]
Output: 11
Explanation: The optimal choice of operations is:
(1 * gcd(3, 6)) + (2 * gcd(4, 8)) = 3 + 8 = 11

Example 3:

Input: nums = [1,2,3,4,5,6]
Output: 14
Explanation: The optimal choice of operations is:
(1 * gcd(1, 5)) + (2 * gcd(2, 4)) + (3 * gcd(3, 6)) = 1 + 4 + 9 = 14

 

Constraints:

  • 1 <= n <= 7
  • nums.length == 2 * n
  • 1 <= nums[i] <= 106

Solution

maximize-score-after-n-operations.py
class Solution:
    def maxScore(self, nums: List[int]) -> int:
        N = len(nums)
        G = [[0] * N for _ in range(N)]
        full_mask = (1 << N) - 1

        for x in range(N):
            for y in range(N):
                G[x][y] = gcd(nums[x], nums[y])

        @cache
        def go(index, mask):
            if mask == full_mask: return 0

            res = 0
            for x in range(N):
                if mask & (1 << x) > 0: continue
                for y in range(x + 1, N):
                    if mask & (1 << y) > 0: continue
                    res = max(res, index * G[x][y] + go(index + 1, mask | (1 << x) | (1 << y)))

            return res

        return go(1, 0)