Skip to main content
Back to problems
#2036
Medium Algorithms

Maximum alternating subarray sum

Array Dynamic Programming
39.9% acceptance
Mar 31, 2026
106
6

No description available.

Solution

Rust
Time O(n)
Space O(1)
LeetCode
solution.rs
impl Solution {
  pub fn maximum_alternating_subarray_sum(nums: Vec<i32>) -> i64 {
    let mut pos = i64::MIN / 2;
    let mut neg = i64::MIN / 2;
    let mut ans = i64::MIN;

    for &x in &nums {
      let x = x as i64;
      let new_pos = x.max(neg + x);
      let new_neg = pos - x;
      pos = new_pos;
      neg = new_neg;
      ans = ans.max(pos).max(neg);
    }

    ans
  }
}