Skip to content

2036. Maximum Alternating Subarray Sum 👍

  • Time: $O(n)$
  • Space: $O(1)$
 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
class Solution {
 public:
  long long maximumAlternatingSubarraySum(vector<int>& nums) {
    long long ans = INT_MIN;
    long long even = 0;  // Subarray sum starting from an even index
    long long odd = 0;   // Subarray sum starting from an odd index

    for (int i = 0; i < nums.size(); ++i) {
      if ((i & 1) == 0)  // Must pick
        even += nums[i];
      else  // Fresh start or minus
        even = max(0LL, even - nums[i]);
      ans = max(ans, even);
    }

    for (int i = 1; i < nums.size(); ++i) {
      if (i & 1)  // Must pick
        odd += nums[i];
      else  // Fresh start or minus
        odd = max(0LL, odd - nums[i]);
      ans = max(ans, odd);
    }

    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
class Solution {
  public long maximumAlternatingSubarraySum(int[] nums) {
    long ans = Integer.MIN_VALUE;
    long even = 0; // Subarray sum starting from an even index
    long odd = 0;  // Subarray sum starting from an odd index

    for (int i = 0; i < nums.length; ++i) {
      if (i % 2 == 0) // Must pick
        even += nums[i];
      else // Fresh start or minus
        even = Math.max(0, even - nums[i]);
      ans = Math.max(ans, even);
    }

    for (int i = 1; i < nums.length; ++i) {
      if (i % 2 == 1) // Must pick
        odd += nums[i];
      else // Fresh start or minus
        odd = Math.max(0, odd - nums[i]);
      ans = Math.max(ans, odd);
    }

    return ans;
  }
}
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
class Solution:
  def maximumAlternatingSubarraySum(self, nums: List[int]) -> int:
    ans = -math.inf
    even = 0  # Subarray sum starting from an even index
    odd = 0  # Subarray sum starting from an odd index

    for i in range(len(nums)):
      if (i & 1) == 0:  # Must pick
        even += nums[i]
      else:  # Fresh start or minus
        even = max(0, even - nums[i])
      ans = max(ans, even)

    for i in range(1, len(nums)):
      if i & 1:  # Must pick
        odd += nums[i]
      else:  # Fresh start or minus
        odd = max(0, odd - nums[i])
      ans = max(ans, odd)

    return ans