#196. 计算路径高度变化总和

    ID: 196 Type: Default 1000ms 256MiB Tried: 0 Accepted: 0 Difficulty: (None) Uploaded By: Tags>codingbatAp-1gesp1循环结构条件结构

计算路径高度变化总和

Calculate Path Height Change Sum

Background

During a hike, you need to calculate the total sum of height changes along a path.

Problem Description

We have an array of heights, representing the altitude along a walking trail. Given start/end indexes into the array, return the sum of the changes for a walk beginning at the start index and ending at the end index, however increases in height count double. For example, with the heights {5,3,6,7,2}\{5, 3, 6, 7, 2\} and start=2start=2, end=4end=4 yields a sum of 1imes2+5=71 imes 2 + 5 = 7. The start and end index will both be valid indexes into the array with start≤endstart \le end.

Input Format

The input is given from standard input in the following format.

heights: An integer array representing altitudes along the path. start: An integer, the starting index. end: An integer, the ending index.

Output Format

Output an integer to standard output in the following format.

sum: An integer, the calculated total sum of height changes.

Sample

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

Sample Explanation

For the first sample [5 3 6 7 2] 2 4:

  • heights[2] = 6, heights[3] = 7, heights[4] = 2.
  • From index 22 to 33: height increases from 66 to 77, change is 7−6=17 - 6 = 1. Since it's an increase, it counts as 1imes2=21 imes 2 = 2.
  • From index 33 to 44: height decreases from 77 to 22, change is ∣2−7∣=5|2 - 7| = 5. Since it's a decrease, it counts as 55.
  • Total sum is 2+5=72 + 5 = 7.

Constraints

Time limit: 1s, Memory limit: 1024KiB.