Program to find maximize score after n operations in Python

We have an array nums of size 2*n and need to perform n operations. In each operation i (1-indexed), we select two elements x and y, get a score of i * gcd(x, y), and remove both elements. The goal is to maximize the total score.

Algorithm Approach

We use dynamic programming with bitmasks to solve this problem. The key insight is that we need to try all possible pairs at each step and choose the combination that gives maximum score ?

  • Use a bitmask to represent which elements are already used

  • For each state, try all possible pairs of unused elements

  • Recursively calculate the maximum score for remaining operations

  • Memoize results to avoid redundant calculations

Example

For nums = [6,2,1,5,4,3], the optimal strategy gives us a score of 14 ?

from math import gcd

def solve(nums):
    n = len(nums)
    dp = [-1] * (1 << n)
    
    def dfs(mask, t):
        # If all elements are used, return 0
        if mask == (1 << n) - 1:
            return 0
        
        # Return memoized result if available
        if dp[mask] != -1:
            return dp[mask]
        
        max_score = 0
        
        # Try all possible pairs of unused elements
        for i in range(n):
            if (1 << i) & mask:  # Skip if element i is already used
                continue
            for j in range(i + 1, n):
                if (1 << j) & mask:  # Skip if element j is already used
                    continue
                
                # Calculate score for this pair and recurse
                current_score = gcd(nums[i], nums[j]) * t
                remaining_score = dfs(mask | (1 << i) | (1 << j), t + 1)
                total_score = current_score + remaining_score
                
                max_score = max(max_score, total_score)
        
        dp[mask] = max_score
        return dp[mask]
    
    return dfs(0, 1)

# Test the function
nums = [6, 2, 1, 5, 4, 3]
result = solve(nums)
print(f"Maximum score: {result}")
Maximum score: 14

How It Works

Let's trace through the optimal solution for [6,2,1,5,4,3] ?

  • Operation 1: Select 1 and 5, score = 1 × gcd(1,5) = 1 × 1 = 1

  • Operation 2: Select 2 and 4, score = 2 × gcd(2,4) = 2 × 2 = 4

  • Operation 3: Select 3 and 6, score = 3 × gcd(3,6) = 3 × 3 = 9

Total score = 1 + 4 + 9 = 14

Time Complexity

The time complexity is O(2^n × n²) where n is the array size. The space complexity is O(2^n) for the memoization table.

Complete Example with Step-by-Step Output

from math import gcd

def solve_with_steps(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]
        
        max_score = 0
        
        for i in range(n):
            if (1 << i) & mask:
                continue
            for j in range(i + 1, n):
                if (1 << j) & mask:
                    continue
                
                current_score = gcd(nums[i], nums[j]) * t
                remaining_score = dfs(mask | (1 << i) | (1 << j), t + 1)
                total_score = current_score + remaining_score
                
                max_score = max(max_score, total_score)
        
        dp[mask] = max_score
        return dp[mask]
    
    return dfs(0, 1)

# Test cases
test_cases = [
    [6, 2, 1, 5, 4, 3],
    [1, 2],
    [3, 4, 6, 8]
]

for i, nums in enumerate(test_cases):
    result = solve_with_steps(nums)
    print(f"Test case {i+1}: {nums}")
    print(f"Maximum score: {result}")
    print()
Test case 1: [6, 2, 1, 5, 4, 3]
Maximum score: 14

Test case 2: [1, 2]
Maximum score: 1

Test case 3: [3, 4, 6, 8]
Maximum score: 11

Conclusion

This dynamic programming solution with bitmasks efficiently finds the maximum score by exploring all possible combinations of element pairs. The key insight is using memoization to avoid recalculating the same subproblems multiple times.

Updated on: 2026-03-26T14:48:11+05:30

544 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements