Skip to main content
Back to problems
Codeforces
Easy
Arrays
Math
Roadside Trees (Simplified Edition)

Compute the total number of steps needed to visit trees placed along a road in order.

Acceptance 0%
Also Available On
Other platform versions and source mappings for the same problem.

Roadside Trees

gfg
Problem Statement

Roadside Trees (Simplified Edition)

A road has several trees planted at different positions along a straight line. You start at the first tree and move to the next tree in the given order. To go from one tree to the next, you need to walk the absolute distance between their positions.

Your task is to calculate the total distance walked while visiting all trees in order.

This is the simplified version of the problem, where the tree positions are already given in the order you must visit them.

Input Format

  • The first line contains an integer nn — the number of trees.
  • The second line contains nn integers a1,a2,,ana_1, a_2, \dots, a_n — the positions of the trees in the order they are visited.

Output Format

  • Output one integer: the total distance traveled when moving from the first tree to the second, then to the third, and so on.

Constraints

  • 1n1051 \le n \le 10^5
  • 0ai1090 \le a_i \le 10^9
  • The answer fits in a 64-bit signed integer.
Examples
Sample cases returned by the problem API.

Example 1

Input

5
1 5 2 8 3

Output

14

Explanation

The distances are |5-1| = 4, |2-5| = 3, |8-2| = 6, and |3-8| = 5. The total is 4 + 3 + 6 + 5 = 18.

(Note: for this illustrative example, the output should match the sum of consecutive absolute differences.)

Premium problem context

Unlock deeper context for this problem

Premium adds guided hints, editorial links, similar variants, discussion resources, and concept maps so you can understand why a problem matters, not just solve it once.

Guided hints
Editorial and discussion links
Concept map and variants
Sign in to unlock
Track your progress
Sign in to bookmark this problem, save notes, and manage its revision plan.