program grand_garden
  implicit none
  integer :: n, h(100) = 0, i
  read(*,*) n
  read(*,*) h(1:n)
  write(*,'(i0)') watering(h(1:n))
contains
  recursive function watering(h) result(res)
    integer, intent(in) :: h(:)
    integer :: n, m, l, r, i, res
    res = 0
    if (maxval(h) == 0) return
    n = size(h)
    m = minval(h)
    res = m
    l = 0
    do r = 1, n
      if (r == n .or. h(r) == m) then
        i = merge(r-1,n,h(r) == m)
        if (l+1 <= i) res = res+watering(h(l+1:i)-m)
        l = r
      end if
    end do
  end
end program grand_garden