Alternating Prefix Sums
EasyPractice library · +10 XPprefix sumsarray manipulation
Given an array of N integers A, compute an array B of the same size where each element B[i] is the sum of elements A[0] through A[i] with alternating signs. Specifically, B[i] = A[0] - A[1] + A[2] - A[3] + ... + (-1)^i * A[i]. Print all elements of array B.
Input
The first line contains a single integer N. The second line contains N space-separated integers A_0, A_1, ..., A_{N-1}.
Output
Print N space-separated integers B_0, B_1, ..., B_{N-1}.
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
1 -1 2 -2 3
B[0]=1; B[1]=1-2=-1; B[2]=1-2+3=2; B[3]=1-2+3-4=-2; B[4]=1-2+3-4+5=3
Example 2
Input
3 10 -5 20
Output
10 15 35
B[0]=10; B[1]=10-(-5)=15; B[2]=10-(-5)+20=35
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
3 10 -5 20