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: 60
💡 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. Wait, let me recalculate: gcd(6,10)=2, so [6,10] gives 16×2=32. But the answer is 60, so there must be a better subarray. Actually, let me check [6,10,3]: sum=19, gcd(6,10,3)=1, gives 19×1=19. Let me reconsider the problem.
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 SubarrayInput: nums = [6, 10, 3], k = 26103[6,10]: 16×2 = 32[10,3]: 13×1 = 13[6,10,3]: 19×1 = 19Maximum GCD-Sum: 32
Understanding the Visualization
1
Input
Array [6,10,3] with k=2 minimum length
2
Process
Calculate sum × gcd for each valid subarray
3
Output
Return maximum gcd-sum value found
Key Takeaway
🎯 Key Insight: The GCD of any subarray must be a divisor of at least one element in it, allowing us to optimize by grouping elements by potential GCD values.
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