Skip to content

3026. Maximum Good Subarray Sum 👍

  • Time: $O(n)$
  • 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
class Solution {
 public:
  long long maximumSubarraySum(vector<int>& nums, int k) {
    long ans = LONG_MIN;
    long prefix = 0;
    // {num: the minimum prefix sum excluding `num`}
    unordered_map<int, long> numToMinPrefix;

    for (const int num : nums) {
      if (const auto it = numToMinPrefix.find(num);
          it == numToMinPrefix.cend() || it->second > prefix) {
        numToMinPrefix[num] = prefix;
      }
      prefix += num;
      if (const auto it = numToMinPrefix.find(num + k);
          it != numToMinPrefix.cend())
        ans = max(ans, prefix - it->second);
      if (const auto it = numToMinPrefix.find(num - k);
          it != numToMinPrefix.cend())
        ans = max(ans, prefix - it->second);
    }

    return ans == LONG_MIN ? 0 : ans;
  }
};
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
class Solution {
  public long maximumSubarraySum(int[] nums, int k) {
    long ans = Long.MIN_VALUE;
    long prefix = 0;
    Map<Integer, Long> numToMinPrefix = new HashMap<>();

    for (final int num : nums) {
      if (!numToMinPrefix.containsKey(num) || numToMinPrefix.get(num) > prefix)
        numToMinPrefix.put(num, prefix);
      prefix += num;
      if (numToMinPrefix.containsKey(num + k))
        ans = Math.max(ans, prefix - numToMinPrefix.get(num + k));
      if (numToMinPrefix.containsKey(num - k))
        ans = Math.max(ans, prefix - numToMinPrefix.get(num - k));
    }

    return ans == Long.MIN_VALUE ? 0 : ans;
  }
}
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
class Solution:
  def maximumSubarraySum(self, nums: list[int], k: int) -> int:
    ans = -math.inf
    prefix = 0
    numToMinPrefix = {}

    for num in nums:
      if num not in numToMinPrefix or numToMinPrefix[num] > prefix:
        numToMinPrefix[num] = prefix
      prefix += num
      if num + k in numToMinPrefix:
        ans = max(ans, prefix - numToMinPrefix[num + k])
      if num - k in numToMinPrefix:
        ans = max(ans, prefix - numToMinPrefix[num - k])

    return 0 if ans == -math.inf else ans