pangfengliu / programmingtasks

programming tasks from my courses
67 stars 17 forks source link

Mountains #325

Open littlehug opened 7 years ago

littlehug commented 7 years ago

Task Description

Write a program to calculate the cost of fuel to go through a series of mountains.

We will go through a series of n mountains. Let m1, m2, … , mn denote the mountains. The height of mi is denoted by hi. We will start from m1, then go m2, then m3, etc, and finally stop at mn.

A transition describes how we get from one mountain to the next. There are two kinds of transitions when we go from mi to mi+1. If hi+1 is greater than hi, then this transition is an uphill. Otherwise, it is a downhill.

There is a cost associated with every transition. The cost of a transition is determined by the type of this transition and the one in front of it. For example, the cost of transition from m4 to m5 is determined by itself and the type of the transition from m3 to m4. There are two cases.

We illustrate the concept with an example of four mountains. Let h1, h2, h3, h4 be 10, 20, 5, and 3.

As a result, the total cost going from m1 to m4 is 30 + 45 + 4 = 79.

Now given the heights of the mountains, please compute the cost going from mountain m1 to mountain mn.

Note that the memory limit is 1MB, so you cannot declare an array to store the heights. As a result, you must remember the heights of the previous two mountains, so that you can calculate the cost when you read the next one.

Input

The input contains two lines. The first line contains an integer n, denoting the number of mountains. The second line contains n integers, denoting h1, h2, …, hn.

2 <= n <= 1000000 1 <= hi <= 500

Output

Output the total cost going from m1 to mn.

Sample Input 1

4
10 20 5 3

Sample Output 1

79

Sample Input 2

4
30 5 20 50

Sample Output 2

215