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
sbe the sum of all the elements ofa. - Let
gbe the greatest common divisor of all the elements ofa. - The gcd-sum of
ais equal tos * 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
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.
💡
Explanation
AI Ready
💡 Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code