Skip to content

3381. Maximum Subarray Sum With Length Divisible by K 👍

  • Time: $O(n)$
  • Space: $O(n)$
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
class Solution {
 public:
  long long maxSubarraySum(std::vector<int>& nums, int k) {
    long ans = LONG_MIN;
    long prefix = 0;
    // minPrefix[i % k] := the minimum prefix sum of the first i numbers
    vector<long> minPrefix(k, LONG_MAX / 2);
    minPrefix[k - 1] = 0;

    for (int i = 0; i < nums.size(); ++i) {
      prefix += nums[i];
      ans = max(ans, prefix - minPrefix[i % k]);
      minPrefix[i % k] = min(minPrefix[i % k], prefix);
    }

    return ans;
  }
};
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
class Solution {
  public long maxSubarraySum(int[] nums, int k) {
    long ans = Long.MIN_VALUE;
    long prefix = 0;
    // minPrefix[i % k] := the minimum prefix sum of the first i numbers
    long[] minPrefix = new long[k];
    Arrays.fill(minPrefix, Long.MAX_VALUE / 2);
    minPrefix[k - 1] = 0;

    for (int i = 0; i < nums.length; ++i) {
      prefix += nums[i];
      ans = Math.max(ans, prefix - minPrefix[i % k]);
      minPrefix[i % k] = Math.min(minPrefix[i % k], prefix);
    }

    return ans;
  }
}
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
class Solution:
  def maxSubarraySum(self, nums: list[int], k: int) -> int:
    ans = -math.inf
    prefix = 0
    # minPrefix[i % k] := the minimum prefix sum of the first i numbers
    minPrefix = [math.inf] * k
    minPrefix[k - 1] = 0

    for i, num in enumerate(nums):
      prefix += num
      ans = max(ans, prefix - minPrefix[i % k])
      minPrefix[i % k] = min(minPrefix[i % k], prefix)

    return ans