Back to Month
MEDIUM 16 Jul 2026 View on LeetCode

3867. Sum of GCD of Formed Pairs

</> Solution

import java.util.*;
class Solution {
    public long gcdSum(int[] nums) {
        int n = nums.length;
        int[] prefixGcd = new int[n];
        int mx = 0;
        for (int i = 0; i < n; i++) {
            mx = Math.max(mx, nums[i]);
            prefixGcd[i] = gcd(nums[i], mx);
        }
        Arrays.sort(prefixGcd);
        long ans = 0;
        int l = 0, r = n - 1;
        while (l < r) {
            ans += gcd(prefixGcd[l], prefixGcd[r]);
            l++;
            r--;
        }
        return ans;
    }
    private int gcd(int a, int b) {
        while (b != 0) {
            int t = a % b;
            a = b;
            b = t;
        }
        return a;
    }
}

TIME COMPLEXITY

O(n log n + n log M)

SPACE COMPLEXITY

O(n)

TOPICS

Array Math Sorting