[LeetCode] Compute Alternating Sum

3701. Compute Alternating Sum

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.

1
2
3
4
5
6
7
8
9
10
class Solution {
public:
int alternatingSum(vector<int>& nums) {
int res = 0;
for(int i = 0, fl = 1; i < nums.size(); i++, fl = -fl) {
res += fl * nums[i];
}
return res;
}
};
Author: Song Hayoung
Link: https://songhayoung.github.io/2025/10/12/PS/LeetCode/compute-alternating-sum/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.