Maximum GCD-Sum of a Subarray Problem
Description
LeetCode Problem 2941.
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.
Example 1:
Input: nums = [2,1,4,4,4,2], k = 2
Output: 48
Explanation: We take the subarray [4,4,4], the gcd-sum of this array is 4 * (4 + 4 + 4) = 48.
It can be shown that we can not select any other subarray with a gcd-sum greater than 48.
Example 2:
Input: nums = [7,3,9,4], k = 1
Output: 81
Explanation: We take the subarray [9], the gcd-sum of this array is 9 * 9 = 81.
It can be shown that we can not select any other subarray with a gcd-sum greater than 81.
Constraints:
n == nums.length1 <= n <= 10^51 <= nums[i] <= 10^61 <= k <= n
Solution
Approach: Distinct GCDs of Subarrays Ending Here
Trying every subarray is too slow. Fix the right end i. As the left end moves left, the gcd of the subarray only goes down, and each change at least halves it, so there are only O(log A) distinct gcd values (A is the largest number).
Keep a list of pairs (j, g) for the current right end: g is the gcd of the subarrays that start at the leftmost index j of that gcd value and end at i. When moving to i + 1, take the gcd of every g with the new number, drop duplicates (keeping the leftmost start), and add the pair for the single-element subarray.
For each pair whose subarray has at least k elements, the best choice for that gcd is the leftmost start, which gives the largest sum. Use prefix sums to get the sum and update the answer with sum * g.
Complexity: O(n log A) time (times a small gcd cost) and O(n) space for the prefix sums.
from itertools import accumulate
from math import gcd
class Solution:
def maxGcdSum(self, nums: List[int], k: int) -> int:
s = list(accumulate(nums, initial=0))
f = []
ans = 0
for i, v in enumerate(nums):
g = []
for j, x in f:
y = gcd(x, v)
if not g or g[-1][1] != y:
g.append((j, y))
f = g
f.append((i, v))
for j, x in f:
if i - j + 1 >= k:
ans = max(ans, (s[i + 1] - s[j]) * x)
return ans