Sum of GCD of Formed Pairs

You are given an integer array nums of length n.

Construct an array prefixGcd where for each index i:

  • Let mxi = max(nums[0], nums[1], ..., nums[i]).
  • prefixGcd[i] = gcd(nums[i], mxi).

After constructing prefixGcd:

  • Sort prefixGcd in non-decreasing order.
  • Form pairs by taking the smallest unpaired element and the largest unpaired element.
  • Repeat this process until no more pairs can be formed.
  • For each formed pair, compute the gcd of the two elements.
  • If n is odd, the middle element in the prefixGcd array remains unpaired and should be ignored.

Return an integer denoting the sum of the GCD values of all formed pairs.

The term gcd(a, b) denotes the greatest common divisor of a and b.

Example 1
Inputnums = [2,6,4]
Output2
prefixGcd = [2, 6, 2], which sorts to [2, 2, 6]; the only formed pair has gcd(2, 6) = 2, and the middle element is ignored.
Example 2
Inputnums = [3,6,2,8]
Output5
prefixGcd = [3, 6, 2, 8], which sorts to [2, 3, 6, 8]; the formed pairs have GCDs gcd(2, 8) = 2 and gcd(3, 6) = 3, so the sum is 5.

Constraints

  • 1 <= n == nums.length <= 10^5
  • 1 <= nums[i] <= 10^​​​​​​​9

Asked at 1 companies

</>

Your Solution

(Ctrl/Cmd + Enter)

Switching Language

Loading template...

Loading...

Sign in to save your progress

AI code evaluation

Get a correctness verdict, missed edge cases, and complexity analysis of your solution.

Sign in to evaluate