n = gets.to_s.to_i y = gets.to_s.split.map{|t| t.to_i } inf = 10**4 * n dp = [inf] * (y.max + 1) dp[0] = 0 m = 0 y.each_with_index do |t, i| m = t if m < t dp[0] = dp[0] + t 1.upto(t) do |j| dp[j] = [dp[j] + t - j, dp[j-1] - 1 ].min end (t+1).upto(m) do |j| dp[j] = [dp[j] + j - t, dp[j-1] + 1 ].min end end ans = dp.min puts ans