#195. 路径海拔变化总和
路径海拔变化总和
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 and start=2, end=4 yields a sum of . 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 , 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 .
The sum of absolute changes in adjacent altitudes is:
$|heights[3] - heights[2]| + |heights[4] - heights[3]|$
Constraints
Time limit: 1 second, Memory limit: 1024 KiB for each test case.