Skip to content

2941. Maximum GCD-Sum of a Subarray 👍

  • Time: O(n \cdot \log(\max(\texttt{nums})) \cdot \log(\log(\max(\texttt{nums}))))
  • Space: $O(n)$
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
class Solution {
 public:
  long long maxGcdSum(vector<int>& nums, int k) {
    long long ans = 0;
    // [(startIndex, gcd of subarray starting at startIndex)]
    vector<pair<int, int>> startIndexAndGcds;
    vector<long long> prefix = {0};

    for (const int num : nums)
      prefix.push_back(prefix.back() + num);

    for (int i = 0; i < nums.size(); ++i) {
      vector<pair<int, int>> nextStartIndexAndGcds;
      for (const auto& [startIndex, gcd] : startIndexAndGcds) {
        const int nextGcd = __gcd(gcd, nums[i]);
        if (nextStartIndexAndGcds.empty() ||
            nextStartIndexAndGcds.back().second != nextGcd)  // Skip duplicates.
          nextStartIndexAndGcds.emplace_back(startIndex, nextGcd);
      }
      startIndexAndGcds = std::move(nextStartIndexAndGcds);
      startIndexAndGcds.emplace_back(i, nums[i]);
      for (const auto& [startIndex, gcd] : startIndexAndGcds)
        if (i - startIndex + 1 >= k)
          ans = max(ans, (prefix[i + 1] - prefix[startIndex]) * gcd);
    }

    return ans;
  }
};
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
class Solution {
  public long maxGcdSum(int[] nums, int k) {
    long ans = 0;
    // [(startIndex, gcd of subarray starting at startIndex)]
    List<Pair<Integer, Integer>> startIndexAndGcds = new ArrayList<>();
    long[] prefix = new long[nums.length + 1];

    for (int i = 0; i < nums.length; ++i)
      prefix[i + 1] = (long) nums[i] + prefix[i];

    for (int i = 0; i < nums.length; ++i) {
      List<Pair<Integer, Integer>> nextStartIndexAndGcds = new ArrayList<>();
      for (Pair<Integer, Integer> pair : startIndexAndGcds) {
        final int startIndex = pair.getKey();
        final int gcd = pair.getValue();
        final int nextGcd = gcd(gcd, nums[i]);
        if (nextStartIndexAndGcds.isEmpty() ||
            !nextStartIndexAndGcds.get(nextStartIndexAndGcds.size() - 1)
                 .getValue()
                 .equals(nextGcd)) // Skip duplicates.
          nextStartIndexAndGcds.add(new Pair<>(startIndex, nextGcd));
      }
      startIndexAndGcds = new ArrayList<>(nextStartIndexAndGcds);
      startIndexAndGcds.add(new Pair<>(i, nums[i]));
      for (Pair<Integer, Integer> pair : startIndexAndGcds) {
        final int startIndex = pair.getKey();
        final int gcd = pair.getValue();
        if (i - startIndex + 1 >= k)
          ans = Math.max(ans, (prefix[i + 1] - prefix[startIndex]) * gcd);
      }
    }

    return ans;
  }

  private int gcd(int a, int b) {
    return b == 0 ? a : gcd(b, a % b);
  }
}
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
class Solution:
  def maxGcdSum(self, nums: list[int], k: int) -> int:
    ans = 0
    # [(startIndex, gcd of subarray starting at startIndex)]
    startIndexAndGcds = []
    prefix = list(itertools.accumulate(nums, initial=0))

    for i, num in enumerate(nums):
      nextStartIndexAndGcds = []
      for startIndex, gcd in startIndexAndGcds:
        nextGcd = math.gcd(gcd, nums[i])
        if (not nextStartIndexAndGcds or
                nextStartIndexAndGcds[-1][1] != nextGcd):  # Skip duplicates.
          nextStartIndexAndGcds.append((startIndex, nextGcd))
      startIndexAndGcds = nextStartIndexAndGcds
      startIndexAndGcds.append((i, nums[i]))
      for startIndex, gcd in startIndexAndGcds:
        if i - startIndex + 1 >= k:
          ans = max(ans, (prefix[i + 1] - prefix[startIndex]) * gcd)

    return ans