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 ans = INT_MIN;
    long even = 0;  // the subarray sum starting from an even index
    long odd = 0;   // the subarray sum starting from an odd index

    for (int i = 0; i < nums.size(); ++i) {
      if (i % 2 == 0)  // Must pick.
        even += nums[i];
      else  // Start a fresh subarray or subtract `nums[i]`.
        even = max(0L, even - nums[i]);
      ans = max(ans, even);
    }

    for (int i = 1; i < nums.size(); ++i) {
      if (i % 2 == 1)  // Must pick.
        odd += nums[i];
      else  // Start a fresh subarray or subtract `nums[i]`.
        odd = max(0L, 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; // the subarray sum starting from an even index
    long odd = 0;  // the 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 // Start a fresh subarray or subtract `nums[i]`.
        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 // Start a fresh subarray or subtract `nums[i]`.
        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  # the subarray sum starting from an even index
    odd = 0  # the subarray sum starting from an odd index

    for i in range(len(nums)):
      if i % 2 == 0:  # Must pick.
        even += nums[i]
      else:  # Start a fresh subarray or subtract `nums[i]`.
        even = max(0, even - nums[i])
      ans = max(ans, even)

    for i in range(1, len(nums)):
      if i % 2 == 1:  # Must pick.
        odd += nums[i]
      else:  # Start a fresh subarray or subtract `nums[i]`.
        odd = max(0, odd - nums[i])
      ans = max(ans, odd)

    return ans