Sum of GCD of Formed Pairs

You are given an integer array nums of length n.

Construct a new array prefixGcd where each element at index i is the Greatest Common Divisor (GCD) of nums[i] and the maximum value found in nums from index 0 to i (inclusive).

After constructing prefixGcd, sort it in non-decreasing order. Continuously pair the smallest unpaired element with the largest unpaired element until no pairs remain. For each pair, compute the GCD of the two elements and return the total sum of all these computed GCDs. (If n is odd, ignore the exact middle element).

Example 1:

Input: nums = [3,6,2,8]

Output: 5

Explanation:

prefixGcd becomes [3, 6, 2, 8]. Sorted, it is [2, 3, 6, 8]. Pairs are (2, 8) and (3, 6). gcd(2, 8) = 2, gcd(3, 6) = 3. Total = 5.

Example 2:

Input: nums = [5]

Output: 0

Explanation:

The length is odd, so the middle element 5 is ignored. No pairs formed. Total is 0.

Now Your Turn!

Pick the correct output for the given input

Input: nums = [4, 8, 2]

Still unsure what the problem is asking ?

Let’s go through a few more examples, step by step, to make it clearer.

Constraints:

  • 1 <= nums.length <= 105
  • 1 <= nums[i] <= 109

Hints

Frequently Occurring Doubts

Interview Follow-up Questions

0
class Solution {
public:
long long sumOfGcdOfFormedPairs(vector<int>& nums) {
}
};
Test Case

Input:

Nums