Cumulative Sum of Differences
EasyPractice library · +10 XPprefix sumsdifference arraysrange queries
Given an array of N integers A. You need to compute the sum of absolute differences between all adjacent pairs of elements. That is, compute (\sum_{i=0}^{N-2} |A[i+1] - A[i]|).
Input
The first line contains an integer N. The second line contains N space-separated integers A_0, A_1, ..., A_{N-1}.
Output
Print a single integer representing the sum of absolute differences between adjacent elements.
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 3 2 5 4
Output
7
Differences are |3-1|=2, |2-3|=1, |5-2|=3, |4-5|=1. Sum = 2+1+3+1 = 7.
Example 2
Input
3 10 10 10
Output
0
All adjacent differences are 0. Sum = 0.
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 3 2 5 4
Example 2 input
3 10 10 10