Skip to content
Onsite

Sum of Absolute Differences of Consecutive Elements

EasyP3Coding

Return the sum of |arr[i + 1] - arr[i]| over all consecutive pairs, using recursion. An array with fewer than two elements has no pairs, so the sum is 0.

Example 1

Input
arr = [1,5,2,8]
Output
13
Why
|5-1| + |2-5| + |8-2| = 4 + 3 + 6 = 13.

Example 2

Input
arr = []
Output
0

Example 3

Input
arr = [4]
Output
0

Constraints

  • 0 <= arr.length <= 500
  • -10^6 <= arr[i] <= 10^6

Hints

Run checks the 3 visible tests, Submit all 8.