# util functions

# debug
$debugFlag = ( ARGV[0] != nil )
p "==== DEBUG MODE ====" if $debugFlag

def pd(str)
  p str if $debugFlag
end

def printd(str)
  print str if $debugFlag
end

# input
inputs = []
lc = 0
while l = $stdin.gets do
  if false
    inputs << l.chomp.split(" ").map(&:to_s)
  else
    inputs << l.chomp.split(" ").map(&:to_i)
  end
  lc += 1
end

lst = inputs[1]

# input check
if $debugFlag
  p "--- INPUT (begin) ---"
  inputs.each do |l_i|
    p l_i
  end
  p "--- INPUT (end) ---"
  print "\n"
end

# body
if $debugFlag
  p lst
end

def proc(arr)
  return arr[0] if arr.size == 1
  
  min = arr.min
  for i in 0..arr.size-1
    arr[i] -= min
  end

  subarr = []
  head = 0
  tail = 0
  while head < arr.size
    while arr[head] != 0 and head < arr.size
      head += 1
    end
    if arr[tail] != 0
      subarr << arr[tail..head-1].clone
    end
    head += 1    
    tail = head
  end

  pd subarr

  ret = min
  subarr.each do |arr_i|
    ret += proc(arr_i)
  end

  return ret
end

puts proc(lst)
