Problem Description
Given an array of integers nums and an integer k, find the maximum gcd-sum of any contiguous subarray of nums with at least k elements. The gcd-sum of an array a is defined as (sum of all elements in a) multiplied by (greatest common divisor of all elements in a).
Key Insights
- The gcd-sum depends on both the sum of elements and their GCD.
- Brute forcing all subarrays is infeasible due to the constraint n ≤ 10^5.
- Instead of iterating over all subarrays, we can iterate potential candidate GCD values.
- For each candidate divisor d, check if there exists a contiguous segment of length at least k such that every element is divisible by d.
- Use a sliding-window or two-pointer technique to quickly sum segments where each element is divisible by the candidate value.
- Multiply the segment’s sum by the candidate divisor to evaluate candidate gcd-sum and track the maximum.
Space and Time Complexity
Time Complexity: Approximately O(max(nums) * n) in the worst-case scenario though practical performance may be better depending on the input distribution. Space Complexity: O(n) for auxiliary arrays used in the sliding window technique.
Solution
The solution iterates through potential divisors (from the maximum element down to 1). For each divisor d, we form a boolean array marking each element as valid if it is divisible by d. Using a sliding window approach, we then scan this boolean array along with the original array to find the maximum subarray sum where every element is valid and the subarray length is at least k. Multiplying this sum by d gives the candidate gcd-sum. The maximum candidate across all divisors is the answer.