Problem:
Score : 300 points

Problem Statement

In a flower bed, there are N flowers, numbered 1,2,......,N. Initially, the heights of all flowers are 0.
You are given a sequence h=\{h_1,h_2,h_3,......\} as input. You would like to change the height of Flower k to h_k for all k (1 \leq k \leq N), by repeating the following "watering" operation:

Specify integers l and r. Increase the height of Flower x by 1 for all x such that l \leq x \leq r.

Find the minimum number of watering operations required to satisfy the condition.

Constraints

1 \leq N \leq 100

0 \leq h_i \leq 100

All values in input are integers.

Input

Input is given from Standard Input in the following format:

N
h_1 h_2 h_3 ...... h_N

Output

Print the minimum number of watering operations required to satisfy the condition.

Sample Input 1

4
1 2 2 1

Sample Output 1

2

The minimum number of watering operations required is 2.
One way to achieve it is:

Perform the operation with (l,r)=(1,3).

Perform the operation with (l,r)=(2,4).

Sample Input 2

5
3 1 2 3 1

Sample Output 2

5

Sample Input 3

8
4 23 75 0 23 96 50 100

Sample Output 3

221

Solution in Ruby (2.3.3) (judge verdict: Accepted)

def w(ar,be,le)
    #pp "ar = #{ar}, be = #{be}, le = #{le}"
    if(le == 0 || ar.length < be+le-1)then return 0 end
    flag = 0
    flag2 = 0
    le.times do |i|
        if ar[be+i] >= 1 then
            flag = 1
        else
            flag2 = 1
        end
        #pp "now i = #{i}, flag = #{flag}, flag2 = #{flag2}"
    end
    if flag == 0 then return 0 # 全て 0 だった場合、水やりができないため 0 を返す
    end
    if flag2 == 0 then # 全てが 1 以上だった場合、すべてに水やりをするため w 関数を再帰呼び出しする
        le.times do|i|
            ar[be+i] -= 1
        end
        return w(ar,be,le) + 1
    end
    
    # まず0じゃないところまで be をずらす #
    count = 0
    while ar[be] <= 0 do
        be +=1
        le -=1
    end
    # 次に 0 のところを見つけて再帰呼び出しをする #
    i = be+1
    flag = 1 # 0 が見つけられなかった場合のフラグ
    while i < (be + le) do
        if ar[i] == 0 then
            count += w(ar,be,i-be) # 0 より前の要素を再帰呼び出し
            count += w(ar,i+1, le-(i-be+1)) # 0 より後の要素を呼び出し
            flag = 0
            break
        end
        i += 1
    end
    if flag == 1 then count += w(ar,be,le) end
    return count
end

len = gets.chomp!.to_i
arr = gets.chomp!.split.map &:to_i

puts w(arr,0,len)