[LeetCode] Sum of GCD of Formed Pairs

3867. 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 mx_i = max(nums[0], nums[1], ..., nums[i]).
  • prefixGcd[i] = gcd(nums[i], mx_i).

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.

gcd(a, b)

greatest common divisor

a

b

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
class Solution {
public:
long long gcdSum(vector<int>& nums) {
vector<long long> g;
for(int i = 0, ma = 0; i < nums.size(); i++) {
ma = max(ma, nums[i]);
g.push_back(__gcd(nums[i], ma));
}
sort(begin(g), end(g));
int l = 0, r = g.size() - 1;
long long res = 0;
while(l < r) {
res += __gcd(g[l], g[r]);
l++,r--;
}
return res;
}
};
Author: Song Hayoung
Link: https://songhayoung.github.io/2026/09/04/PS/LeetCode/sum-of-gcd-of-formed-pairs/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.