Alternating Sum
EasyPractice library · +10 XPprefix sumsloopsbasic arithmetic
Given a list of N integers, compute the alternating sum. The alternating sum is defined as the sum of elements at even indices (0, 2, 4, ...) minus the sum of elements at odd indices (1, 3, 5, ...). Indices are 0-based.
Input
The first line contains an integer N. The second line contains N space-separated integers.
Output
Print a single integer representing the alternating sum.
Constraints
1 <= N <= 1000 -1000 <= A[i] <= 1000
Time limit 1 s (native code; slower languages get more)Memory 256 MB14 hidden tests
Example 1
Input
5 1 2 3 4 5
Output
3
Even indices: 1, 3, 5. Odd indices: 2, 4. Sum = (1 + 3 + 5) - (2 + 4) = 9 - 6 = 3.
Example 2
Input
4 10 20 30 40
Output
-20
Even indices: 10, 30. Odd indices: 20, 40. Sum = (10 + 30) - (20 + 40) = 40 - 60 = -20.
Hints
# Read the input from stdin and print the answer.
import sys
def main():
data = sys.stdin.read().split()
# your code here
main()
Example 1 input
5 1 2 3 4 5
Example 2 input
4 10 20 30 40