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.

Input & Output

Example 1 — Basic Case
$ Input: nums = [1,2,3,4,5,6]
Output: 14
💡 Note: One optimal sequence: Operation 1: choose (1,5) → 1×gcd(1,5) = 1×1 = 1. Operation 2: choose (2,4) → 2×gcd(2,4) = 2×2 = 4. Operation 3: choose (3,6) → 3×gcd(3,6) = 3×3 = 9. Total score = 1 + 4 + 9 = 14.
Example 2 — Same Elements
$ Input: nums = [3,4,6,8]
Output: 11
💡 Note: Optimal sequence: Operation 1: choose (3,6) → 1×gcd(3,6) = 1×3 = 3. Operation 2: choose (4,8) → 2×gcd(4,8) = 2×4 = 8. Total score = 3 + 8 = 11.
Example 3 — Minimum Case
$ Input: nums = [1,2]
Output: 1
💡 Note: Only one operation possible: choose (1,2) → 1×gcd(1,2) = 1×1 = 1.

Constraints

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

Visualization

Tap to expand
Maximize Score After N Operations INPUT nums array (size 2*n = 6) 1 2 3 4 5 6 0 1 2 3 4 5 n = 3 operations GCD Values gcd(1,2)=1 gcd(1,3)=1 gcd(1,4)=1 gcd(1,5)=1 gcd(1,6)=1 gcd(2,3)=1 gcd(2,4)=2 gcd(2,5)=1 gcd(2,6)=2 gcd(3,4)=1 gcd(3,5)=1 gcd(3,6)=3 gcd(4,5)=1 gcd(4,6)=2 gcd(5,6)=1 Best GCDs: 3,2,2 (use later ops) ALGORITHM STEPS 1 Bitmask DP Setup Use mask to track used elements (0-63 states) 2 Try All Pairs For each state, try all pairs of unused elements 3 Calculate Score score = i * gcd(x,y) i = operation number 4 Maximize Recursively dp[mask] = max score from current state Optimal Pairing Op 1: (1,5) --> 1*1 = 1 Op 2: (2,4) --> 2*2 = 4 Op 3: (3,6) --> 3*3 = 9 FINAL RESULT Maximum Score Calculation Operation 1: 1 * 1 = 1 Operation 2: 2 * 2 = 4 Operation 3: 3 * 3 = 9 Total: 1+4+9 = 14 Output: 14 OK - Verified Key Insight: Use bitmask DP to efficiently track which elements have been used. Higher operation numbers multiply the GCD score, so save the best GCD pairs (like gcd(3,6)=3) for later operations to maximize total score. Time: O(2^(2n) * n^2), Space: O(2^(2n)) TutorialsPoint - Maximize Score After N Operations | Bitmask DP Approach
Asked in
Google 15 Microsoft 12 Amazon 8
23.5K Views
Medium Frequency
~25 min Avg. Time
890 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen