Maximum GCD-Sum of a Subarray - Problem

You are given an array of integers nums and an integer k.

The gcd-sum of an array a is calculated as follows:

  • Let s be the sum of all the elements of a.
  • Let g be the greatest common divisor of all the elements of a.
  • The gcd-sum of a is equal to s * g.

Return the maximum gcd-sum of a subarray of nums with at least k elements.

Input & Output

Example 1 — Basic Case
$ Input: nums = [6,10,3], k = 2
Output: 32
💡 Note: Subarray [6,10] has sum=16, gcd=gcd(6,10)=2, so gcd-sum = 16×2 = 32. Subarray [10,3] has sum=13, gcd=1, gcd-sum=13. Subarray [6,10,3] has sum=19, gcd=1, gcd-sum=19. Maximum is 32.
Example 2 — All Elements
$ Input: nums = [4,4,4,4], k = 3
Output: 48
💡 Note: Any subarray of length 3 has sum=12 and gcd=4, giving gcd-sum = 12×4 = 48
Example 3 — Minimum Length
$ Input: nums = [5,10], k = 2
Output: 75
💡 Note: Only one subarray [5,10]: sum=15, gcd(5,10)=5, gcd-sum = 15×5 = 75

Constraints

  • 1 ≤ nums.length ≤ 103
  • 1 ≤ k ≤ nums.length
  • 1 ≤ nums[i] ≤ 106

Visualization

Tap to expand
Maximum GCD-Sum of a Subarray INPUT Array nums: 6 idx 0 10 idx 1 3 idx 2 k = 2 (min length) Subarrays (len >= 2): [6, 10] sum=16, gcd=2 [10, 3] sum=13, gcd=1 [6, 10, 3] sum=19, gcd=1 ALGORITHM STEPS 1 Group by GCD Find all unique GCDs 2 Calculate GCD-Sums gcd-sum = sum * gcd Subarray Sum GCD Result [6,10] 16 2 32 [10,3] 13 1 13 [6,10,3] 19 1 19 3 Optimize Search Higher GCD can give larger products 4 Find Maximum Track max gcd-sum FINAL RESULT Optimal Subarray Found: [6, 10] indices 0 to 1 Calculation: sum = 6 + 10 = 16 gcd = gcd(6, 10) = 2 gcd-sum = 16 * 2 = 32 OUTPUT 60 Maximum GCD-Sum Key Insight: GCD-Based Grouping Group elements by their GCD values. For each unique GCD g, find subarrays where all elements are divisible by g. Larger GCDs with sufficient sums can beat smaller GCDs. Time complexity: O(n * max(nums) / min_prime_factor) using divisor enumeration. TutorialsPoint - Maximum GCD-Sum of a Subarray | GCD-Based Grouping Approach
Asked in
Google 15 Microsoft 12 Amazon 8
8.5K Views
Medium Frequency
~35 min Avg. Time
245 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen