We use cookies (including Google cookies) to personalize ads and analyze traffic. By continuing to use our site, you accept our Privacy Policy.

Maximize Score After N Operations

Number: 1906

Difficulty: Hard

Paid? No

Companies: Bloomberg, Walmart Labs, Sprinklr


Problem Description

Given an array nums of 2 * n positive integers, perform n operations where in the iᵗʰ operation you:

  • Pick any two remaining numbers x and y.
  • Gain a score of i * gcd(x, y) (where gcd is the greatest common divisor).
  • Remove x and y from nums. Return the maximum score possible after exactly n operations.

Key Insights

  • Use a bitmask or state representation to track which numbers have been picked.
  • With n up to 7 (i.e., nums size up to 14), the total number of states (2^(2*n)) is manageable.
  • Use recursion with memoization (DP) to avoid recalculating results for the same state.
  • Pre-calculate gcd for each pair of numbers to optimize the inner loop.
  • The order of operations matters because each operation multiplies the gcd by the current operation index.

Space and Time Complexity

Time Complexity: O(2^(2n) * (2n)^2) – since for each state represented by a bitmask, we attempt pairing available numbers. Space Complexity: O(2^(2*n)) – for the memoization cache.


Solution

We use a bitmask to represent the state of the array (each bit represents whether an element is used). We perform a DFS to try all possible pairs of unused numbers. At each recursive call:

  1. Count the number of operations already performed (derived from the number of bits set).
  2. Identify the operation multiplier as (number of operations performed + 1).
  3. For every pair of unused numbers, compute the added score from the pair (multiplier * gcd(value1, value2)).
  4. Recursively compute the maximum score from the new state after marking these two elements as used.
  5. Use memoization to cache and quickly return the computed result for a given bitmask state. This algorithm explores all pairing combinations ensuring that we maximize the total score.

Code Solutions

# Import math module to use gcd function
import math
from functools import lru_cache

def maximizeScore(nums):
    n = len(nums) // 2  # n operations to be performed

    # Use memoization to cache results for each bitmask state.
    @lru_cache(maxsize=None)
    def dp(mask):
        used_count = bin(mask).count("1")
        # If all numbers are used, return a score of 0.
        if used_count == len(nums):
            return 0
        
        # Determine current operation number (1-indexed)
        op_num = used_count // 2 + 1
        max_score = 0
        
        # Try every possible pair of unused numbers.
        for i in range(len(nums)):
            if mask & (1 << i):
                continue  # i already used
            for j in range(i + 1, len(nums)):
                if mask & (1 << j):
                    continue  # j already used
                # Select pair (i, j) and compute current score.
                new_mask = mask | (1 << i) | (1 << j)
                current_score = op_num * math.gcd(nums[i], nums[j])
                # Recursively compute remaining score.
                total_score = current_score + dp(new_mask)
                max_score = max(max_score, total_score)
        return max_score

    return dp(0)

# Example usage:
# print(maximizeScore([3,4,6,8]))  # Expected output: 11
← Back to All Questions