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: Strategic PairingInput: [1,2,3,4,5,6]123456Strategy: Save pairs with high GCD for later operations (higher multipliers)Op 1: (1,5)1×gcd(1,5)=1Op 2: (2,4)2×gcd(2,4)=4Op 3: (3,6)3×gcd(3,6)=9Maximum Score: 1 + 4 + 9 = 14Key: Later operations have higher multipliers!
Understanding the Visualization
1
Input
Array of 2n positive integers
2
Process
Choose pairs strategically - save high GCD pairs for later operations
3
Output
Maximum possible score from n operations
Key Takeaway
🎯 Key Insight: Save pairs with highest GCD for later operations since they get multiplied by larger operation numbers
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