Skip to main content
Back to problems
Leetcode
Medium
Arrays
Number Theory
Dynamic Programming
Google
Maximize Pair Strength Using Gcd

Choose pairings from an array to maximize the total strength contributed by each pair, where each pair’s contribution is based on the GCD of its two values.

Acceptance 0%
Problem Statement

You are given an array of positive integers. In one operation, you may choose any two unused numbers, form a pair, and earn a score equal to the operation index multiplied by the gcd of the chosen pair.

If you perform kk pair-formation operations, the first pair earns 1×gcd(a,b)1 \times gcd(a,b), the second earns 2×gcd(c,d)2 \times gcd(c,d), and so on up to k×gcd(⋅,⋅)k \times gcd(\cdot,\cdot). Every number can be used at most once.

Your task is to maximize the total score by selecting which numbers to pair and in what order to create the pairs.

Input Format

  • An integer array nums of even length.
  • Each element represents a positive integer available for pairing.

Output Format

Return the maximum possible total score achievable by pairing all numbers optimally.

Constraints

  • nums.length is even.
  • All values in nums are positive integers.
  • The array size is small enough to allow state-compression search / DP over subsets.
Examples
Sample cases returned by the problem API.

Example 1

Input

nums = [1,2,3,4]

Output

5

Explanation

One optimal pairing order is to pair (2,4) first for 1 * gcd(2,4) = 2, then pair (1,3) for 2 * gcd(1,3) = 2. Total = 4. Another ordering can yield 5 if the better GCD pair is used later with a larger multiplier, depending on the exact pair choices. This example illustrates that pairing order matters.

Premium problem context

Unlock deeper context for this problem

Premium adds guided hints, editorial links, similar variants, discussion resources, and concept maps so you can understand why a problem matters, not just solve it once.

Guided hints
Editorial and discussion links
Concept map and variants
Sign in to unlock
Track your progress
Sign in to bookmark this problem, save notes, and manage its revision plan.