#3701
Easy Algorithms Compute alternating sum
Array Simulation
89.7% acceptance
Feb 24, 2026
63
2
You are given an integer array nums.
The alternating sum of nums is the value obtained by adding elements at even
indices and subtracting elements at odd indices. That is, nums[0] - nums[1] + nums[2] - nums[3]...
Return an integer denoting the alternating sum of nums.
Solution
Rust
Time O(n)
Space O(1)
impl Solution {
pub fn alternating_sum(nums: Vec<i32>) -> i32 {
nums.iter().enumerate().map(|(i, &v)| if i % 2 == 0 { v } else { -v }).sum()
}
}