Maximum GCD-Sum of a Subarray - Problem
Maximum GCD-Sum of a Subarray
You are given an array of integers
The GCD-sum of an array is calculated as:
• Let
• Let
• The GCD-sum =
Goal: Return the maximum GCD-sum possible from any subarray of
Example: For array
• Subarray
• Subarray
• Subarray
Maximum GCD-sum = 32
You are given an array of integers
nums and an integer k. Your task is to find the maximum GCD-sum among all possible subarrays with at least k elements.The GCD-sum of an array is calculated as:
• Let
s be the sum of all elements in the array• Let
g be the greatest common divisor (GCD) of all elements• The GCD-sum =
s × gGoal: Return the maximum GCD-sum possible from any subarray of
nums that contains at least k elements.Example: For array
[6, 10, 3] with k = 2:• Subarray
[6, 10]: sum = 16, GCD = 2, GCD-sum = 32• Subarray
[10, 3]: sum = 13, GCD = 1, GCD-sum = 13• Subarray
[6, 10, 3]: sum = 19, GCD = 1, GCD-sum = 19Maximum GCD-sum = 32
Input & Output
example_1.py — Basic case
$
Input:
nums = [6, 10, 3], k = 2
›
Output:
32
💡 Note:
We need subarrays with at least 2 elements. Subarray [6,10] has sum=16 and GCD=2, so GCD-sum = 16×2 = 32. This is the maximum among all valid subarrays.
example_2.py — All elements have GCD 1
$
Input:
nums = [7, 5, 6, 2], k = 3
›
Output:
18
💡 Note:
The subarray [7,5,6] has sum=18 and GCD=1, giving GCD-sum=18. Even though other subarrays exist, this one has the maximum sum since all have GCD=1.
example_3.py — High GCD with smaller sum
$
Input:
nums = [12, 16, 8], k = 2
›
Output:
112
💡 Note:
Subarray [12,16] has sum=28 and GCD=4, giving GCD-sum=112. Subarray [12,16,8] has sum=36 and GCD=4, giving GCD-sum=144. The maximum is 144.
Visualization
Tap to expand
Understanding the Visualization
1
Identify treasure groups
Group treasures by their common factors (potential multipliers)
2
Calculate collection values
For each group, find the best collection of k+ treasures
3
Apply magic multiplier
Multiply the treasure sum by the GCD multiplier
4
Choose the richest collection
Select the collection with maximum treasure × multiplier value
Key Takeaway
🎯 Key Insight: Elements with higher common factors can produce better results even with smaller sums, so we should prioritize subarrays where elements share meaningful divisors rather than just focusing on maximum sum.
Time & Space Complexity
Time Complexity
O(n × d × log n)
Where d is the number of distinct divisors, n log n for sorting/searching within each group
⚡ Linearithmic
Space Complexity
O(n × d)
Space to store elements grouped by their divisors
⚡ Linearithmic Space
Constraints
- 1 ≤ nums.length ≤ 104
- 1 ≤ k ≤ nums.length
- -109 ≤ nums[i] ≤ 109
- At least one valid subarray must exist
💡
Explanation
AI Ready
💡 Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code