Skip to content

3701. Compute Alternating Sum

Description

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.

 

Example 1:

Input: nums = [1,3,5,7]

Output: -4

Explanation:

  • Elements at even indices are nums[0] = 1 and nums[2] = 5 because 0 and 2 are even numbers.
  • Elements at odd indices are nums[1] = 3 and nums[3] = 7 because 1 and 3 are odd numbers.
  • The alternating sum is nums[0] - nums[1] + nums[2] - nums[3] = 1 - 3 + 5 - 7 = -4.

Example 2:

Input: nums = [100]

Output: 100

Explanation:

  • The only element at even indices is nums[0] = 100 because 0 is an even number.
  • There are no elements on odd indices.
  • The alternating sum is nums[0] = 100.

 

Constraints:

  • 1 <= nums.length <= 100
  • 1 <= nums[i] <= 100

Solutions

Solution 1: Simulation

We can directly traverse the array \(\textit{nums}\). For each index \(i\), if \(i\) is even, we add \(\textit{nums}[i]\) to the answer; otherwise, we subtract \(\textit{nums}[i]\) from the answer.

Finally, we return the answer.

The time complexity is \(O(n)\), where \(n\) is the length of array \(\textit{nums}\). The space complexity is \(O(1)\).

1
2
3
class Solution:
    def alternatingSum(self, nums: List[int]) -> int:
        return sum(nums[0::2]) - sum(nums[1::2])
1
2
3
4
5
6
7
8
9
class Solution {
    public int alternatingSum(int[] nums) {
        int ans = 0;
        for (int i = 0; i < nums.length; ++i) {
            ans += (i % 2 == 0 ? nums[i] : -nums[i]);
        }
        return ans;
    }
}
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
class Solution {
public:
    int alternatingSum(vector<int>& nums) {
        int ans = 0;
        for (int i = 0; i < nums.size(); ++i) {
            ans += (i % 2 == 0 ? nums[i] : -nums[i]);
        }
        return ans;
    }
};
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
func alternatingSum(nums []int) (ans int) {
    for i, x := range nums {
        if i%2 == 0 {
            ans += x
        } else {
            ans -= x
        }
    }
    return
}
1
2
3
4
5
6
7
function alternatingSum(nums: number[]): number {
    let ans: number = 0;
    for (let i = 0; i < nums.length; ++i) {
        ans += i % 2 === 0 ? nums[i] : -nums[i];
    }
    return ans;
}

Comments