#1799

Maximize Score After N Operations

Hard
ArrayMathDynamic ProgrammingBacktrackingBit ManipulationNumber TheoryBitmask
LeetCode ↗

Approaches

💡

Intuition

Time Space

The brute force approach involves generating all possible pairs of elements from the array and calculating the score for each combination. This method is straightforward but inefficient as it explores all combinations exhaustively.

⚙️

Algorithm

3 steps
  1. 1Step 1: Generate all combinations of pairs from the nums array.
  2. 2Step 2: For each combination, calculate the score using the formula i * gcd(x, y) where i is the operation number.
  3. 3Step 3: Keep track of the maximum score obtained through all combinations.
solution.py20 lines
1# Full working Python code
2import itertools
3import math
4def maxScore(nums):
5    n = len(nums) // 2
6    def backtrack(used, score, op):
7        if op > n:
8            return score
9        max_score = 0
10        for i in range(len(nums)):
11            if used[i]: continue
12            for j in range(i + 1, len(nums)):
13                if used[j]: continue
14                used[i] = used[j] = True
15                current_score = op * math.gcd(nums[i], nums[j])
16                max_score = max(max_score, backtrack(used, score + current_score, op + 1))
17                used[i] = used[j] = False
18        return max_score
19    return backtrack([False] * len(nums), 0, 1)
20

Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.