#include <bits/stdc++.h>   using namespace std;   const long long MOD = 1e9 + 7;   long long n, n2 = 1, a[5010], dat[20010], ans = 0;   vector<long long> v, vv[5010];   map<long long, long long> mp;   void build(long long k, long long lb, long long ub) {     if (lb == ub) return;     build(k * 2 + 1, lb, (lb + ub) / 2);     build(k * 2 + 2, (lb + ub) / 2 + 1, ub);     dat[k] = min(dat[k * 2 + 1], dat[k * 2 + 2]);   }   long long query(long long k, long long lb, long long ub, long long tlb,                   long long tub) {     if (ub < tlb || tub < lb) return 2e9;     if (tlb <= lb && ub <= tub) return dat[k];     return min(query(k * 2 + 1, lb, (lb + ub) / 2, tlb, tub),                query(k * 2 + 2, (lb + ub) / 2 + 1, ub, tlb, tub));   }   long long dfs(long long lb, long long ub, long long lst) {     if (lb > ub) return 0;     long long ret = ub - lb + 1, mn = query(0, 0, n2 - 1, lb, ub), res = mn - lst;     long long num = mp[mn],               pos = lower_bound(vv[num].begin(), vv[num].end(), lb) -                     vv[num].begin(),               pos2 = lower_bound(vv[num].begin(), vv[num].end(), ub + 1) -                      vv[num].begin() - 1;     for (long long i = pos; i < pos2; i++)       res += dfs(vv[num][i] + 1, vv[num][i + 1] - 1, mn);     res += dfs(lb, vv[num][pos] - 1, mn) + dfs(vv[num][pos2] + 1, ub, mn);     ret = min(ret, res);     return ret;   }   int main() {     cin >> n;     for (int i = 0; i < n; i++) {       scanf( %I64d , &a[i]);       v.push_back(a[i]);     }     sort(v.begin(), v.end());     v.erase(unique(v.begin(), v.end()), v.end());     for (int i = 0; i < v.size(); i++) mp[v[i]] = i;     for (int i = 0; i < n; i++) vv[mp[a[i]]].push_back(i);     while (n2 < n) n2 *= 2;     for (int i = 0; i < 20005; i++) dat[i] = 1e18;     for (int i = 0; i < n; i++) dat[i + n2 - 1] = a[i];     build(0, 0, n2 - 1);     cout << dfs(0, n - 1, 0) << endl;     return 0;   }   