#195. 路径海拔变化总和

    ID: 195 Type: Default 1000ms 256MiB Tried: 0 Accepted: 0 Difficulty: (None) Uploaded By: Tags>codingbatAp-1gesp1循环结构数学基础

路径海拔变化总和

Sum of Altitude Changes

Background

Congcong and his friends are planning a hiking trip. They have a map recording the altitudes along the trail, and now they want to calculate the total change in altitude for a specific segment of the path.

Problem Description

We are given an array of heights, representing the altitude along a walking trail. Given start and end indexes into the array, return the sum of the absolute changes for a walk beginning at the start index and ending at the end index. For example, with the heights {5,3,6,7,2}\{5, 3, 6, 7, 2\} and start=2, end=4 yields a sum of 1+5=61 + 5 = 6. The start and end indexes will both be valid indexes into the array with start <= end.

Input Format

Input is given from Standard Input in the following format.

[h_0 h_1 ... h_{N-1}] start end

Where h_i are the altitudes, start is the starting index, and end is the ending index.

Output Format

Output is printed to Standard Output in the following format.

sum_of_changes

Where sum_of_changes is the sum of absolute changes in adjacent altitudes for the specified path.

Sample

[5 3 6 7 2] 2 4
6
[5 3 6 7 2] 0 1
2
[5 3 6 7 2] 0 4
11

Sample Explanation

For the first sample, the altitude array is {5,3,6,7,2}\{5, 3, 6, 7, 2\}, the starting index is start=2, and the ending index is end=4. The path segment to calculate is from heights[2] to heights[4], which is {6,7,2}\{6, 7, 2\}. The sum of absolute changes in adjacent altitudes is: $|heights[3] - heights[2]| + |heights[4] - heights[3]|$ =76+27= |7 - 6| + |2 - 7| =1+5= 1 + 5 =6= 6

Constraints

Time limit: 1 second, Memory limit: 1024 KiB for each test case.