jiahuimbzuai/CoQuIR huggingface dataset:
//  [swift]
import Foundation

extension String {
    
    func toStrList() -> [String] {
        return self.map{String($0)}
    }
    
    func toIntList() -> [Int] {
        return self.map{Int(String($0))!}
    }
    
    func toSepDoubleList() -> [Double]{
        return self.split(separator: " ").map{Double($0)!}
    }

    func toSepIntList() -> [Int] {
        return self.split(separator: " ").map{Int($0)!}
    }

    func toSepStrList() -> [String] {
        return self.split(separator: " ").map{String($0)}
    }
    
    func zFill(n:Int) -> String {
        return String(format: "%0\(n)d", Int(self)!)
    }
    
    func count(c:Character) -> Int{
        var result = 0

        for e in self{
            if e == c{
                result += 1
            }
        }
        return result
    }

    func counter() -> Dictionary<Character, Int>{
        var result:[Character:Int] = [:]
        
        for c in self{
            guard let _ = result.index(forKey: c) else {
                result[c] = 1
                continue
            }
            result[c]! += 1
        }
        return result
    }
}

extension Int {
    func toBin() -> String {
        return String(self, radix: 2)
    }
    
    func toNBin(_ radix:Int) -> String{
        return String(self, radix: radix)
    }
    
    func toD() -> Double {
        return Double(self)
    }
}

extension Double {
    func toI() -> Int {
        return Int(self)
    }
}

extension Array where Element: Equatable{
    func count(n:Self.Element) -> Int{
        var result = 0
        for e in self{
            if e == n{
                result += 1
            }
        }
        return result
    }
}

extension Array {
    func dump(){
        for x in 0..<self.count-1{
            print(self[x], terminator: " ")
        }
        print(self.last!)
    }
}

func pow(_ base:Int,_ exp:Int) -> Int{
    let d = pow(base.toD(), exp.toD())
    return Int(d)
}

func distance(p1:CGPoint, p2:CGPoint) -> Double {
    let diffp = CGPoint(x:p1.x - p2.x, y:p1.y - p2.y)
    return Double(sqrt(diffp.x*diffp.x + diffp.y * diffp.y))
}

func distance(p1:[Double], p2:[Double]) -> Double{
    let diff = [p1[0] - p2[0], p1[1] - p2[1]]
    return sqrt(diff[0] * diff[0] + diff[1] * diff[1])
    
}

func lotate(theta:Double, point:[Double]) -> [Double] {
    let matrix = [
        [cos(theta), -sin(theta)],
        [sin(theta), cos(theta)]
    ]
    let x = point[0]
    let y = point[1]
    
    let rx = matrix[0][0]*x + matrix[0][1]*y
    let ry = matrix[1][0]*x + matrix[1][1]*y
    
    return [rx, ry]
}




func abc079a() -> String {
    let N = readLine()!.toIntList()
    if N[0] == N[1] && N[1] == N[2] {
        return "Yes"
    }
    if N[1] == N[2] && N[2] == N[3] {
        return "Yes"
    }
    return "No"
}


print(abc079a())
//  [swift]
let i=readLine()!.characters.map{$0};print(i[1]==i[2]&&i[0]==i[1]||i[2]==i[3] ?"Yes":"No")
//  [swift]
let i=readLine()!.characters.map{$0};print(i[0]==i[1]||i[2]==i[3]&&i[1]==i[2] ?"Yes":"No")
//  [swift]
import Glibc
extension String: CollectionType {}

//var abc = readLine()!.split(" ").map { Int($0)! }
var n = Int(readLine()!)!
var a = n / 1000
var b = (n % 1000) / 100
var c = (n % 100) / 10
var d = n % 10
if (a == b && b == c) || (a == c && c == d) || (b == c && c == d) || (a == b && b == d) {
  print("Yes")
} else {
  print("No")
}
//  [typescript]
const stdin = require('fs').readFileSync('/dev/stdin', 'utf8')

const s = stdin.split('\n')[0].split('')

const res = s.filter((e,i)=>{
  if(i === 0 || i === s.length - 1)return 0
  return s[i+1] === e && s[i-1] === e ? 1 : 0
}).length

console.log(res > 0 ? 'Yes' : 'No')
//  [typescript]
const main = ()=>{
  let [a,b,c,d] = t.s().split('')
  t.o(a==b&&b==c||b==c&&c==d?'Yes':'No')
}
const t = {
  // 入力
  input: require('fs').readFileSync('/dev/stdin', 'utf8').split(/[\s]/),
  // number型取得
  n: (arg:number = 0):any => {
    if(arg) {
      const a:number[]=[];
      for(let i = 0;i < arg; i++) {
        a.push(t.n());
      }
      return a;
    } else {
      const a = t.input[0];
      t.input.shift();
      return Number(a);
    }
  },
  // string型取得
  s: (arg:number = 0):any => {
    if(arg) {
      const a:string[]=[];
      for(let i = 0;i < arg; i++) {
        a.push(t.s());
      }
      return a;
    } else {
      const a = t.input[0];
      t.input.shift();
      return String(a);
    }
  },
  // char型取得
  c: (arg:number = 0):any => {
    if(arg) {
      const a:string[]=[];
      for(let i = 0;i < arg; i++) {
        a.push(t.c());
      }
      return a;
    } else {
      let a = t.input[0].split('');
      const b = a[0];
      a.shift();
      if (a.length > 0) {
        t.input[0] = a.join('');
      } else {
        t.input.shift();
      }
      return String(b);
    }
  },
  o: (...arg)=>{
    console.log(...arg);
  },
  abs: (a)=>{
    return Math.abs(a);
  },
  min: (a)=>{
    return Math.min(a);
  },
  max: (a)=>{
    return Math.max(a);
  },
  floor: (a)=>{
    return Math.floor(a);
  },
  asc: (ar:number[]) => {
    return ar.sort((a,b)=>{return a-b});
  },
  desc: (ar:number[]) => { 
    return ar.sort((a,b)=>{return b-a});
  },
  sw: (a,arr:any[],op:'=='|'>='|'>'|'<='|'<'='==')=>{
    for(let i=0;i<arr.length;i+=2){
        if(eval(a+op+arr[i]))return arr[i+1]
    }
    return arr[arr.length-1];
  }
}
main()
//  [typescript]
import * as fs from 'fs';

namespace AtCoder {
    export interface Paramable {
        readonly args: string[][];
    }

    export interface Task {
        main(this: Task): void;
    }
}

namespace AtCoder.abc079 {
    export class TaskA implements AtCoder.Task, AtCoder.Paramable {
        public constructor(public readonly args: string[][]) {
        }

        public main(this: TaskA): void {
            const n: number[] = this.args[0][0].split('').map(Number);
            if (n[0] === n[1] && n[1] === n[2]) {
                console.log('Yes');
            } else if (n[1] === n[2] && n[2] === n[3]) {
                console.log('Yes');
            } else {
                console.log('No');
            }
        }
    }

    const args: string[][] = fs.readFileSync('/dev/stdin', 'utf8').trim().split('\n').map(r => r.split(' '));
    const task: AtCoder.Task = new TaskA(args);
    task.main();
}
//  [typescript]
import * as fs from 'fs';

namespace AtCoder {
    export interface Paramable {
        readonly args: string[][];
    }

    export interface Task {
        main(this: Task): void;
    }
}

namespace AtCoder.abc079 {
    export class TaskA implements AtCoder.Task, AtCoder.Paramable {
        public constructor(public readonly args: string[][]) {
        }

        public main(this: TaskA): void {
            const n: number[] = this.args[0][0].split('').map(Number);
            if (n[0] === n[1] && n[1] === n[2] && n[2] === n[3]) {
                console.log('Yes');
            } else if (n[1] === n[2] && n[2] === n[3] && n[3] === n[4]) {
                console.log('Yes');
            } else {
                console.log('No');
            }
        }
    }

    const args: string[][] = fs.readFileSync('/dev/stdin', 'utf8').trim().split('\n').map(r => r.split(' '));
    const task: AtCoder.Task = new TaskA(args);
    task.main();
}
//  [typescript]
import * as fs from 'fs';

namespace AtCoder {
    export interface Paramable {
        readonly args: string[][];
    }

    export interface Task {
        main(this: Task): void;
    }
}

namespace AtCoder.abc079 {
    export class TaskA implements AtCoder.Task, AtCoder.Paramable {
        public constructor(public readonly args: string[][]) {
        }

        public main(this: TaskA): void {
            const n: number[] = this.args[0][0].split('').map(Number);
            if (n[0] === n[1] && n[1] === n[2] && n[2] === n[3]) {
                console.log('Yes');
            }
            if (n[1] === n[2] && n[2] === n[3] && n[3] === n[4]) {
                console.log('Yes');
            } else {
                console.log('No');
            }
        }
    }

    const args: string[][] = fs.readFileSync('/dev/stdin', 'utf8').trim().split('\n').map(r => r.split(' '));
    const task: AtCoder.Task = new TaskA(args);
    task.main();
}
//  [typescript]
import * as readline from "readline";

/* ここに処理を書く */
const main = (args: any[]) => {
  const num: number = args[0];
  const numStr: string = num.toString();
  
  const numArray: string[] = numStr.split('');
  let matchCount = 0;
  for(let i=0;i<numArray.length-1;i++){
  	if(numArray[i] === numArray[2]) matchCount++;
    else matchCount = 0;
    
    if(matchCount>=2) {
      console.log("Yes");
      return;
    }
  }
  console.log("No");
  return;
};

/* 標準入力処理 */
const stdin = (main: Function) => {
  const args: any[] = [];
  const reader = readline.createInterface({
    input: process.stdin,
    output: process.stdout
  });
  reader.on("close", function() {
    main(args);
  });
  reader.on("line", function(line: any) {
    if (line === "") {
      reader.close();
    }
    line.split(" ").forEach((arg: any) => {
      args.push(isNaN(arg) ? arg : Number(arg));
    });
  });
};
/* 実行 */
stdin(main);
//  [python]
n=int(input())
l=list(map(int,input().split()))
a=0
for i in range(len(l)):
    if a<=l[i]:
        a,l[i]=l[i],l[i]-a
    else:
        a=l[i]
        l[i]=0
ans=0
for i in l:
    ans+=i
print(ans)
//  [python]
n = int(input())
h_list = list(map(int,input().split()))

mizu = 0

for i in range(len(h_list)-1):
    if h_list[i] > h_list[i+1]:
        mizu += h_list[i] - h_list[i+1]
        
mizu += h_list[-1]

print(mizu)
//  [python]
N = int(input())
H = [0] + [int(a) for a in input().split()]

a = 0
for i in range(1, N+1):
    a += max(H[i]-H[i-1], 0)

print(a)
//  [python]
import sys
def LI(): return list(map(int, sys.stdin.buffer.readline().split()))
def I(): return int(sys.stdin.buffer.readline())
def LS(): return sys.stdin.buffer.readline().rstrip().decode('utf-8').split()
def S(): return sys.stdin.buffer.readline().rstrip().decode('utf-8')
def IR(n): return [I() for i in range(n)]
def LIR(n): return [LI() for i in range(n)]
def SR(n): return [S() for i in range(n)]
def LSR(n): return [LS() for i in range(n)]
def SRL(n): return [list(S()) for i in range(n)]
def MSRL(n): return [[int(j) for j in list(S())] for i in range(n)]
mod = 10 ** 9 + 7

n = I()
hl = LI()
# count = 0

# len_h = len(hl)

# def m1(n):
#     if n > 0:
#         n = n - 1
#     else:
#         n = 0
#     return n

# max_hana = max(hl)
# if max_hana == 0:
#     print(0)
#     sys.exit()

# for i in range(max_hana):
#     for j in range(len_h):
#         if j == 0:
#             if hl[j] > 0:
#                 count += 1
#         else:
#             if hl[j] > 0 and hl[j-1] == 0:
#                 count += 1
#             elif hl[j] > 0 and hl[j-1] == 0:
#                 count += 1
#     hl = list(map(m1, hl))

# print(count)

######################
# 隣との差分を考えたほうが早い

# 1    2    4    2    1    0      計4
#   1    2    0    0     0

ans = hl[0]
for i in range(1, n)
    ans += max(0, hl[i] - hl[i - 1])
print(ans)
//  [python]
import sys
def LI(): return list(map(int, sys.stdin.buffer.readline().split()))
def I(): return int(sys.stdin.buffer.readline())
def LS(): return sys.stdin.buffer.readline().rstrip().decode('utf-8').split()
def S(): return sys.stdin.buffer.readline().rstrip().decode('utf-8')
def IR(n): return [I() for i in range(n)]
def LIR(n): return [LI() for i in range(n)]
def SR(n): return [S() for i in range(n)]
def LSR(n): return [LS() for i in range(n)]
def SRL(n): return [list(S()) for i in range(n)]
def MSRL(n): return [[int(j) for j in list(S())] for i in range(n)]
mod = 10 ** 9 + 7

n = I()
hl = LI()
# count = 0

# len_h = len(hl)

# def m1(n):
#     if n > 0:
#         n = n - 1
#     else:
#         n = 0
#     return n

# max_hana = max(hl)
# if max_hana == 0:
#     print(0)
#     sys.exit()

# for i in range(max_hana):
#     for j in range(len_h):
#         if j == 0:
#             if hl[j] > 0:
#                 count += 1
#         else:
#             if hl[j] > 0 and hl[j-1] == 0:
#                 count += 1
#             elif hl[j] > 0 and hl[j-1] == 0:
#                 count += 1
#     hl = list(map(m1, hl))

# print(count)

######################
# 隣との差分を考えたほうが早い

# 1    2    4    2    1    0      計4
#   1    2    0    0     0

ans = hl[0]
for i in range(1, N)
    ans += max(0, hl[i] - hl[i - 1])
print(ans)
//  [python]
import sys
def LI(): return list(map(int, sys.stdin.buffer.readline().split()))
def I(): return int(sys.stdin.buffer.readline())
def LS(): return sys.stdin.buffer.readline().rstrip().decode('utf-8').split()
def S(): return sys.stdin.buffer.readline().rstrip().decode('utf-8')
def IR(n): return [I() for i in range(n)]
def LIR(n): return [LI() for i in range(n)]
def SR(n): return [S() for i in range(n)]
def LSR(n): return [LS() for i in range(n)]
def SRL(n): return [list(S()) for i in range(n)]
def MSRL(n): return [[int(j) for j in list(S())] for i in range(n)]
mod = 10 ** 9 + 7

n = I()
hl = LI()
wl = []
count = 0

len_h = len(hl)

def m1(n):
    if n > 0:
        n = n - 1
    else:
        n = 0
    return n

max_hana = max(hl)
if max_hana == 0:
    print(0)

for i in range(max_hana):
    for j in range(len_h):
        if j == 0:
            if hl[j] > 0:
                count += 1
        else:
            if hl[j] > 0 and hl[j-1] == 0:
                count += 1
            elif hl[j] > 0 and hl[j-1] == 0:
                count += 1
    hl = list(map(m1, hl))

print(count)
//  [java]
import java.io.*;
import java.util.*;

public class Main {

	final static long MOD = 1000000007;
	public static String[] Ws = null;
	public static int wsIndx = 0;
	public static BufferedReader in = null;
	public static long cnt=0;
	public static void main(String[] args) throws Exception {
		solution(args);
		if(in!=null){
			in.close();
		}
	}

	public static void solution(String[] args) throws Exception{
		int N = nextInt();

		long[] h = nextLongs();
		long ans =0;
		int st=0;

		while(st!=N){
			for(int i=st;i<N;i++){
				if(h[st]==0){
					st=st+1;
				}else{
					break;
				}
			}
			long min=Long.MAX_VALUE;
			int eIdx=N;
			for(int i=st;i<N;i++){
				if(h[i]==0){
					eIdx=i;
					break;
				}
				min=Math.min(min, h[i]);
			}
			for(int i=st;i<eIdx;i++){
				h[i]-=min;
			}
			if(min!=Long.MAX_VALUE){
				ans+=min;
			}
		}
		System.out.println(ans);
	}





	public static void check() throws Exception{
		if(in == null){
			in = new BufferedReader(new InputStreamReader(System.in));
		}
		if(Ws==null || Ws.length<=wsIndx){
			Ws = in.readLine().split(" ");
			wsIndx=0;
		}
	}
	public static int nextInt()throws Exception{
		check();
		return Integer.parseInt(Ws[wsIndx++]);
	}

	public static long nextLong()throws Exception{
		check();
		return Long.parseLong(Ws[wsIndx++]);
	}

	public static String nextString()throws Exception{
		check();
		return Ws[wsIndx++];
	}

	public static int[] nextInts()throws Exception{
		check();
		int[] tmp = new int[Ws.length];
		for(int i=0;i<tmp.length;i++){
			tmp[i]=Integer.parseInt(Ws[i]);
		}
		wsIndx=Ws.length;
		return tmp;
	}

	public static long[] nextLongs()throws Exception{
		check();
		long[] tmp = new long[Ws.length];
		for(int i=0;i<tmp.length;i++){
			tmp[i]=Long.parseLong(Ws[i]);
		}
		wsIndx=Ws.length;
		return tmp;
	}

	public static String[] nextStrings()throws Exception{
		check();
		wsIndx=Ws.length;
		return Ws;
	}

}
//  [java]
import java.util.Scanner;

public class Main {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        int s = sc.nextInt();
        if(s == 1 || s == 2) {
            System.out.println(4);
            return;
        }
        int ans = 1;
        while(true) {
            if(s == 1) {
                ans++;
                break;
            }
            if(s % 2 == 0) {
                s /= 2;
            } else {
                s = s * 3 + 1;
            }
            ans++;
        }
        System.out.println(ans);
    }
}
//  [java]
import java.util.*;

public class Main {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);

        int N = sc.nextInt();
        int h[] = new int[N];

        for (int i = 0; i < N; i++) {
            h[i] = sc.nextInt();
        }

        boolean mizuyari = true;
        int count = 0;
        while (mizuyari) {
            mizuyari = false;
            for (int i = 0; i < N; i++) {
                if (h[i] > 0) {
                    mizuyari = true;
                    h[i] = h[i] - 1;
                }
            }
            if (mizuyari) {
                count++;
            }
        }

        System.out.println(count);
        sc.close();
    }
}
//  [java]
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.StringTokenizer;

public class Main {
	public static void main(String[] args) {
		FastScanner sc = new FastScanner(System.in);
		int n = sc.nextInt();
		int[] h = new int[n];
		for(int i = 0; i < n; i++) {
			h[i] = sc.nextInt();
		}
		int min = 0, block = 0, allmin = 100;
		int ans = 0;
		for(int i = 1; i < n; i++) {
			if(h[i] < h[i-1]) {
				ans += h[i-1];
				min = h[i];
				block++;
				if(min < allmin) {
					allmin = min;
				}
			}
		}
		ans += min;
		ans -= allmin * block ;
		System.out.println(ans);
	}
	
	static class FastScanner {
		private BufferedReader reader = null;
	    private StringTokenizer tokenizer = null;
	    public FastScanner(InputStream in) {
	        reader = new BufferedReader(new InputStreamReader(in));
	        tokenizer = null;
	    }

	    public String next() {
	        if (tokenizer == null || !tokenizer.hasMoreTokens()) {
	            try {
	                tokenizer = new StringTokenizer(reader.readLine());
	            } catch (IOException e) {
	                throw new RuntimeException(e);
	            }
	        }
	        return tokenizer.nextToken();
	    }

	    public String nextLine() {
	        if (tokenizer == null || !tokenizer.hasMoreTokens()) {
	            try {
	                return reader.readLine();
	            } catch (IOException e) {
	                throw new RuntimeException(e);
	            }
	        }

	        return tokenizer.nextToken("\n");
	    }

	    public long nextLong() {
	        return Long.parseLong(next());
	    }

	    public int nextInt() {
	        return Integer.parseInt(next());
	    }

	    public double nextDouble() {
	         return Double.parseDouble(next());
	     }

	    public int[] nextIntArray(int n) {
	        int[] a = new int[n];
	        for (int i = 0; i < n; i++)
	            a[i] = nextInt();
	        return a;
	    }

	    public long[] nextLongArray(int n) {
	        long[] a = new long[n];
	        for (int i = 0; i < n; i++)
	            a[i] = nextLong();
	        return a;
	    }
	}
}
//  [cpp]
#include <cstdio>
#include <cstdlib>
#include <iostream>
#include <fstream>
#include <sstream>
#include <set>
#include <map>
#include <vector>
#include <list>
#include <algorithm>
#include <cstring>
#include <cmath>
#include <string>
#include <queue>
#include <bitset>     //UWAGA - w czasie kompilacji musi byc znany rozmiar wektora - nie mozna go zmienic
#include <cassert>
#include <iomanip>        //do setprecision
#include <ctime>
#include <complex>
using namespace std;

#define FOR(i,b,e) for(int i=(b);i<(e);++i)
#define FORQ(i,b,e) for(int i=(b);i<=(e);++i)
#define FORD(i,b,e) for(int i=(b)-1;i>=(e);--i)
#define REP(x, n) for(int x = 0; x < (n); ++x)

#define ST first
#define ND second
#define PB push_back
#define MP make_pair
#define LL long long
#define ULL unsigned LL
#define LD long double

const double pi = 3.141592653589793238462643383279502884197169399375105820974944592307816406286208998628034825342;
const int mod=1000000007;

int main(){
	int n;
	cin>>n;
	int h[111]={};
	FOR(i,0,n)cin>>h[i];
	int cnt=h[0];
	FOR(i,1,n){
		if(h[i]==h[i-1]){

		}else if(h[i]>h[i-1]){
			cnt+=h[i]-h[i-1];
		}else{

		}
	}
	cout<<cnt<<endl;
    return 0;
}
//  [cpp]
//https://atcoder.jp/contests/abc116/tasks/abc116_c
#include<bits/stdc++.h>
using namespace std;
typedef long long LL;
#ifdef BTK
#define DEBUG if(1)
#else
#define CIN_ONLY if(1)
struct cww {cww() {CIN_ONLY{ios::sync_with_stdio(false); cin.tie(0);}}}star;
#define DEBUG if(0)
#endif
#define ALL(v) (v).begin(),(v).end()
#define REC(ret, ...) std::function<ret (__VA_ARGS__)>
template <typename T>inline bool chmin(T &l, T r){bool a = l>r; if (a)l = r; return a;}
template <typename T>inline bool chmax(T &l, T r){bool a = l<r; if (a)l = r; return a;}
template <typename T>istream& operator>>(istream &is, vector<T> &v){for (auto &it : v)is >> it;return is;}
class reverse_range {private:struct I {int x;int operator*() {return x-1;}bool operator!=(I& lhs) {return x>lhs.x;}void operator++() {--x;}};I i, n;public:reverse_range(int n) :i({ 0 }), n({ n }){}reverse_range(int i, int n) :i({ i }), n({ n }){}I& begin() {return n;}I& end() {return i;}};
class range {private: struct I { int x; int operator*() { return x; }bool operator!=(I& lhs) { return x<lhs.x; }void operator++() { ++x; } }; I i, n;public:range(int n) :i({ 0 }), n({ n }) {}range(int i, int n) :i({ i }), n({ n }) {}I& begin() { return i; }I& end() { return n; }reverse_range operator!(){return reverse_range(*i,*n);}};


int main(){
    int ret=0;
    int N;
    cin>>N;
    int b=0;
    for(int i:range(N)){
        int a;
        cin>>a;
        ret+=a;
        ret-=min(a,b);
        b=a;
    }
    cout<<ret<<endl;
    return 0;
}
//  [cpp]
#include <bits/stdc++.h>
using namespace std;
#define FOR(i,k,n) for(int i = (int)(k); i < (int)(n); i++)
#define REP(i,n) FOR(i,0,n)
#define ALL(a) a.begin(), a.end()
#define MS(m,v) memset(m,v,sizeof(m))
typedef long long ll;
typedef long double ld;
typedef vector<int> vi;
typedef vector<string> vs;
typedef pair<int, int> pii;
const int MOD = 1e9 + 7;
template<class T> T &chmin(T &a, const T &b) { return a = min(a, b); }
template<class T> T &chmax(T &a, const T &b) { return a = max(a, b); }
template<class T>
istream& operator >> (istream& is, vector<T>& v)
{
	for (auto &i : v) is >> i;
	return is;
}
template<class T>
ostream& operator<<(ostream& os, vector<T>& v)
{
	const string delimiter = "\n";
	REP(i, v.size())
	{
		os << v[i];
		if (i != v.size() - 1) os << delimiter;
	}
	return os;
}
/*--------------------template--------------------*/

int cal(vi v)
{
	if (v.size() == 0) return 0;
	int k = *min_element(ALL(v));
	REP(i, v.size()) v[i] -= k;
	int ans = k;
	vi t;
	REP(i, v.size())
	{
		if (v[i] == 0)
		{
			ans += cal(t);
			t.clear();
		}
		else
		{
			t.push_back(v[i]);
		}
	}
	ans += cal(t);
	return ans;
}

int main()
{
	cin.sync_with_stdio(false); cout << fixed << setprecision(10);
	int n; cin >> n;
	vi v(n); cin >> v;
	cout << cal(v) << endl;
	return 0;
}
//  [cpp]
#include<bits/stdc++.h>
#define rep(i,n) for(int i=0; i<(n); i++)
using namespace std;
using ll=long long;

int main(){
 int n,count=0,a=0;
 cin >> n;
 vector<int> goal(n),len(n,0);
 rep(i,n) cin >> goal[i];

 while(a<n){
  if(len[a]==goal[a]) a++;
  if(len[a]<goal[a]){
   for(int j=a; j<n; j++){
     if(len[j]<goal[j]) len[j] += 1;
     if(len[j]==goal[j]){ 
       count++;
       break;
     }
   }
  }
 }
  cout << count << endl;
}
//  [cpp]
#include<bits/stdc++.h>
#define rep(i,n) for(int i=0; i<(n); i++)
using namespace std;
using ll=long long;

int main(){
 int n,count=0,a=0;
 cin >> n;
 vector<int> goal(n),len(n,0);
 rep(i,n) cin >> goal[i];

 while(a<n){
  if(len[a]==goal[a]) i++;
  if(len[a]<goal[a]){
   for(int j=a; j<n; j++){
     if(len[j]<goal[j]) len[j] += 1;
     if(len[j]==goal[j]){ 
       count++;
       break;
     }
   }
  }
 }
  cout << count << endl;
}
//  [cpp]
#include<bits/stdc++.h>
#define rep(i,n) for(int i=0; i<(n); i++)
using namespace std;
using ll=long long;

int main(){
 int n,count=0,a=0;
 cin >> n;
 vector<int> goal(n),len(n,0);
 rep(i,n) cin >> goal[i];

 while(int a<n){
  if(len[a]==goal[a]) i++;
  if(len[a]<goal[a]){
   for(int j=a; j<n; j++){
     if(len[j]<goal[j]) len[j] += 1;
     if(len[j]==goal[j]){ 
       count++;
       break;
     }
   }
  }
 }
  cout << count << endl;
}
//  [c]
#include<stdio.h>
#include<stdlib.h>

typedef long long ll;

int max(int a, int b){
  if(a > b) return a;
  else return b;
}
int min(int a, int b){
  if(a < b) return a;
  else return b;
}

int sort(const void *a ,const void *b){
  return *(int*)a - *(int*)b;
}

int main(){
  int n,ans=0,now=0;
  scanf("%d",&n);
  int a[n];
  for(int i = 0; i < n; ++i){
    scanf("%d",a+i);
  }

  for(int i = 0; i < n; ++i){
    if(now < a[i]){
      ans += a[i] -now;
      now = a[i];
    }
    else now = a[i];
  }

  printf("%d",ans);
  return 0;

}
//  [c]
#include <stdio.h>
int main(void){
    int n,i,ans=0,now=0;
    scanf("%d",&n);
    int a[n];
    for(i=0;i<n;i++){
        scanf("%d",&a[i]);
    }
    for(i=0;i<n;i++){
        if(now<a[i]){
            ans+=a[i]-now;
            now=a[i];
        }
        else now = a[i];
    }
    printf("%d",ans);
}
//  [c]
#include <stdio.h>

int proc(int* h, int N) {
  int count = 0;
  int needLoop = 0;
  int ptr = 0;
  while(1) {
    while (ptr < N && h[ptr] == 0) ptr += 1;
    if (ptr == N) {
      if (needLoop) {
        needLoop = 0;
        ptr = 0;
        continue;
      } else break;
    }
    needLoop = 1;
    // where h[lptr..rptr] > 0
    count += 1;
    while (h[ptr] > 0) {
      h[ptr++] -= 1;
      if (ptr == N) {
        ptr = 0;
        goto CONT;
      }
    }
CONT:
    continue;
  }
  return count;
}

int main() {
  int N;
  scanf("%d", &N);
  int h[N];
  for (int i = 0; i < N; ++i)
    scanf("%d", &h[i]);

  printf("%d\n", proc(h, N));
  return 0;
}
//  [c]
#include<stdio.h>
int main()
{
  int N;
  int ans=0;
  int h[100]={};
  scanf("%d",&N);
        for(int i=0;i<N;i++) scanf("%d",&h[i]);
  for(int c=0;c<=100000;c++)
  {
  {
    for(int i=0;i<N;i++)
    {
      if(h[i]>0)
      {
        for(int j=1;j<N-j;j++)
        {
          if(h[i+j]==0)
          {
            for(int k=i;k<=i+j-1;k++)
            {
              h[k]--;
            }
            ans++;
            break;
          }
        }
      }
    }
             
  }
  }
        printf("%d",ans);
      return 0;
}
//  [c]
#include<stdio.h>
int main()
{
  int N;
  int ans=0;
  int h[100]={};
  scanf("%d",&N);
        for(int i=0;i<N;i++) scanf("%d",&h[i]);
  for(int c=0;c<=100000;c++)
  {
  {
    for(int i=0;i<N;i++)
    {
      if(h[i]>0)
      {
        for(int j=1;j<N-j;j++)
        {
          if(h[i+j]==0)
          {
            for(int k=i;k<=i+j-1;k++)
            {
              h[k]--;
            }
            ans++;
          }
        }
      }
    }
             
  }
  }
        printf("%d",ans);
      return 0;
}
//  [c]
#include<stdio.h>
int main()
{
  int N;
  int ans=0;
  int h[100]={};
  scanf("%d",&N);
        for(int i=0;i<N;i++) scanf("%d",&h[i]);
  for(int c=0;c<=100;c++)
  {
  {
    for(int i=0;i<N;i++)
    {
      if(h[i]>0)
      {
        for(int j=1;j<N-j;j++)
        {
          if(h[i+j]==0)
          {
            for(int k=i;k<=i+j-1;k++)
            {
              h[k]--;
            }
            ans++;
          }
        }
      }
    }
             
  }
  }
        printf("%d",ans);
      return 0;
}
//  [javascript]
Main(myin());
function myin(){return require("fs").readFileSync("/dev/stdin", "utf8").trim();}
function myout(t){console.log(t);}//standard output
function myerr(t){console.error(t);}//standard error
//[no]param
//不明値:何もしない  1:数値へ変換  2:半角SPで分割  3:改行で分割  4:半角SPで分割し、数値配列へ
//5:改行で分割し、数値配列へ  6:1文字に分割  7:1文字に分割し、数値配列へ
//8:半角SPで結合　9:改行で結合　0:文字なしで結合
function myconv(i,no){switch(no){case 1:return parseInt(i);case 2:return i.split(" ");case 3:return i.split("\n");case 4:return i.split(" ").map((a)=>Number(a));case 5:return i.split("\n").map((a)=>Number(a));case 6:return i.split("");case 7:return i.split("").map((a)=>Number(a));case 8:return i.join(" ");case 9:return i.join("\n");case 0:return i.join("");default:return i;}}
function Main(input) {
  input = myconv(input,3);
  var N = myconv(input[0],1);
  var list = myconv(input[1],4);
  var output = 0;
  var max = Math.max.apply(null,list);
  for(var i = 0; i < max; i++){
    var check = false;
    for(var j = 0; j < N; j++){
      if(list[j] != 0){
        if(!check){
         check = true;
          output++;
        }
        list[j]--;
      }else{
        check = false;
      }
    }
  }
  myout(output);
}
//  [javascript]
"use strict";
    
const main = arg => {
    arg = arg.trim().split("\n");
    const N = parseInt(arg[0].split(" ")[0]);
    const h = arg[1].split(" ").map(n=>parseInt(n));
    
    const state = [...Array(N)].fill(0);
    let answer  = 0;
    let action  = 0;
    
    for(let i=0; i<N; i++) {
        if(action >= h[i]) {
            action = h[i];
        } else {
            answer += h[i] - action;
            action = h[i];
        }
    }
    
    console.log(answer);
}
main(require('fs').readFileSync('/dev/stdin', 'utf8'));
//  [javascript]
function Main(input){
	input = input.split("\n");
  input.shift()
  input = input[0].split(" ").map(a=>~~a);
  
  return saiki(input,0);
}

function saiki(arr,zero){
	if(arr.length==0)return 0;
  var minInd = 0;
  var minVal = arr[0];
  var len = arr.length;
  for(var i = 1; i < len;i++){
  	var v = arr[i];
    if(minVal > v){
    	minInd = i;
      minVal = v;
    }
  }
  var left = arr.slice(0,minInd);
  var right = arr.slice(minInd+1);
  return (minVal-zero) + saiki(left,minVal) + saiki(right,minVal);
}

// If you are interested in the algorithms I used, 
// there is no need to read down from this line.

((b,c,d)=>"undefined"!=typeof require?console.log(Main(require("fs").readFileSync("/dev/stdin","utf8"))):[b=b.split("\n").slice(1,-1).join("\n"),c=function(){try{return Main(b)}catch(f){return f.stack||f.message}}(),d=typeof c,"string"==d||(c=JSON.stringify(c)),$("<form>").append([[10,b],0,[1,d],0,[10,c]].map(f=>$(f?"<textarea>":"<br>",f&&{rows:f[0],cols:40,text:f[1]}))).appendTo("body")])(`
8
4 23 75 0 23 96 50 100
`);
//  [javascript]
"use strict";

function totalH(H) {
    return H.reduce((a,b)=>a+b)
}

function main(arg) {
    const input = arg.trim().split("\n");
    const N = Number(input.shift())
    const H = input[0].split(" ").map(h=>Number(h))
    
    //console.log(N)
    //console.log(H)

    let counter = 0
    while(totalH(H) > 0) {
        // find where is the largest part in current layer
        let len = 0, maxLen=0, lastH=N-1
        for(let i=0; i<N; i++) {
            if(H[i]>0) {
                len++
                //console.log(`len countup ->${len}`)
            } else {
                //console.log(`len=${len}`)
                if(maxLen < len) {
                    //console.log(`i=${i}, len=${len}`)
                    maxLen = len-1
                    lastH=i-1
                }
                len=0
            }
        }
        if(len==N) maxLen = N-1
        let l=lastH-maxLen, r=lastH
        //console.log(`maxLen=${maxLen}, lastH=${lastH}, l=${l}, r=${r}`)
        for(let i=l; i<=r; i++) {
            if(H[i]>0) {
                H[i]--
            }
        }
        //console.log(H)
        counter++
    }
    console.log(counter)
}

main(require("fs").readFileSync("/dev/stdin", "utf8"));
//  [javascript]
"use strict";

function totalH(H) {
    return H.reduce((a,b)=>a+b)
}

function main(arg) {
    const input = arg.trim().split("\n");
    const N = Number(input.shift())
    const H = input[0].split(" ").map(h=>Number(h))
    
    //console.log(N)
    //console.log(H)

    let counter = 0
    while(totalH(H) > 0) {
        // find where is the largest part in current layer
        let len = 0, maxLen=0, lastH=N-1
        for(let i=0; i<N; i++) {
            if(H[i]>0) {
                len++
            } else {
                //console.log(`len=${len}`)
                if(maxLen < len) {
                    maxLen = len
                    lastH=i
                }
                len=0
            }
        }
        if(len==N) maxLen = N
        let l=lastH-maxLen, r=lastH
        //console.log(`maxLen=${maxLen}, lastH=${lastH}, l=${l}, r=${r}`)
        for(let i=l; i<=r; i++) {
            if(H[i]>0) {
                H[i]--
            }
        }
        //console.log(H)
        counter++
    }
    console.log(counter)
}

main(require("fs").readFileSync("/dev/stdin", "utf8"));
//  [javascript]
function main(input){
  const args=input.split("\n");
  const N=parseInt(args[0],10);

  //花の高さh1, h2, …を入れた配列
  const heights=input.split('\n')[1].split(' ').map((n) => parseInt(n, 10));
  const Max=Math.max.apply(null, heights);

  //特定の高さにおけるチャンク数を計算して配列に入れる
  var changArr=[];
  for(var i=1; i<=Max; i++){
    //高さiにおける花の数
    var hananoKazu=heights.filter(function(a){return(a>=i)}).length;
    //高さi以上の花それぞれ、「その1つ後にも高さi以上の花が存在する」場合にマイナス処理
    for(var j=0; j<N; j++){
      if(heights[j]>=i && heights[j+1]>=i){
        hananoKazu--
      }
    }
    //それをしてできた値が「高さiにおけるチャンクの数」である。
    changArr.push(hananoKazu);
  }
  //console.log(changArr);
  
  var setsuyakuKaisuu=[];
  for(var i=1; i<=Max; i++){
    var hananoKazu=heights.filter(function(a){return(a>=i)}).length;
    setsuyakuKaisuu.push(hananoKazu-changArr[i-1])
  }
  //console.log(setsuyakuKaisuu);

  const totalHeight=heights.reduce(function(total, data){return total + data});
  const setsuyakuSum=setsuyakuKaisuu.reduce(function(total, data){return total + data});
  console.log(totalHeight-setsuyakuSum);
}

main(require('fs').readFileSync('/dev/stdin', 'utf8'))
//  [go]
package main

import (
	"bufio"
	"fmt"
	"os"
	"sort"
	"strconv"
)

func out(x ...interface{}) {
	fmt.Println(x...)
}

var sc = bufio.NewScanner(os.Stdin)

func getInt() int {
	sc.Scan()
	i, e := strconv.Atoi(sc.Text())
	if e != nil {
		panic(e)
	}
	return i
}

func getString() string {
	sc.Scan()
	return sc.Text()
}

// min, max, asub, absなど基本関数
func max(a, b int) int {
	if a > b {
		return a
	}
	return b
}

func min(a, b int) int {
	if a < b {
		return a
	}
	return b
}

func asub(a, b int) int {
	if a > b {
		return a - b
	}
	return b - a
}

func abs(a int) int {
	if a >= 0 {
		return a
	}
	return -a
}

func lowerBound(a []int, x int) int {
	idx := sort.Search(len(a), func(i int) bool {
		return a[i] >= x
	})
	return idx
}

func upperBound(a []int, x int) int {
	idx := sort.Search(len(a), func(i int) bool {
		return a[i] > x
	})
	return idx
}

func main() {
	sc.Split(bufio.ScanWords)
	N := getInt()
	h := make([]int, N)
	for i := 0; i < N; i++ {
		h[i] = getInt()
	}

	ans := 0
	for {
		l := 0
		for i := 0; i < N; i++ {
			if h[i] != 0 {
				break
			}
			l++
		}
		mi := 10000
		r := l
		for i := l; i < N; i++ {
			if h[i] == 0 {
				break
			}
			mi = min(mi, h[i])
			r++
		}
		// out(l, r, h)
		if l == r {
			break
		}
		for i := l; i < r; i++ {
			h[i] -= mi
		}
		ans += mi
	}
	out(ans)
}
//  [go]
package main

import (
	"bufio"
	"fmt"
	"os"
	"strconv"
	"strings"
)

func water(l int, r int, h []int) []int {
	for i := l; i < r; i++ {
		h[i] -= 1
	}
	return h
}

func main() {
	var n int
	var s []string
	count := 0
	sc := bufio.NewScanner(os.Stdin)
	if sc.Scan() {
		nt := sc.Text()
		n, _ = strconv.Atoi(nt)
	}
	var h []int
	if sc.Scan() {
		s = strings.Split(sc.Text(), " ")
		for i := 0; i < len(s); i++ {
			hn, _ := strconv.Atoi(s[i])
			h = append(h, hn)
		}
	}

	index := 0
	for {
		l := -1
		r := len(h)
		for i := index; i < n; i++ {
			if l == -1 && h[i] != 0 {
				l = i
				index = i
				continue
			}
			if l != -1 && h[i] == 0 {
				r = i
				break
			}
		}

		if l == -1 {
			break
		}
		h = water(l, r, h)
		count += 1
	}
	fmt.Print(count)
}
//  [go]
package main

import (
	"bufio"
	"fmt"
	"io"
	"os"
	"sort"
	"strconv"
)

func main() {
	n := readi()
	a := make([]int, n)
	for i := 0; i < n; i++ {
		a[i] = readi()
	}

	ans := 0
	for {
		s, ok := start(a)
		if !ok {
			break
		}
		for i := s; i < n; i++ {
			if a[i] == 0 {
				break
			} else {
				a[i] = a[i] - 1
			}
		}
		ans++
	}

	fmt.Println(ans)
}

func start(slice []int) (int, bool) {
	for i, v := range slice {
		if v != 0 {
			return i, true
		}
	}
	return 0, false
}

func equal(a, b []int) bool {
	if len(a) != len(b) {
		return false
	}
	for i, v := range a {
		if v != b[i] {
			return false
		}
	}
	return true
}

/*-------------------utilities-------------------*/

func abs(x int) int {
	if x < 0 {
		return -x
	}
	return x
}

func min(x, y int) int {
	if x < y {
		return x
	}
	return y
}

func max(x, y int) int {
	if x > y {
		return x
	}
	return y
}

func chmin(x *int, y int) bool {
	if *x > y {
		*x = y
		return true
	}
	return false
}

func chmax(x *int, y int) bool {
	if *x < y {
		*x = y
		return true
	}
	return false
}

func gcd(a, b int) int {
	if b == 0 {
		return a
	}
	return gcd(b, a%b)
}

func lcm(a, b int) int {
	return (a * b) / gcd(a, b)
}

func permutations(arr []int) [][]int {
	var helper func([]int, int)
	res := [][]int{}

	helper = func(arr []int, n int) {
		if n == 1 {
			tmp := make([]int, len(arr))
			copy(tmp, arr)
			res = append(res, tmp)
		} else {
			for i := 0; i < n; i++ {
				helper(arr, n-1)
				if n%2 == 1 {
					tmp := arr[i]
					arr[i] = arr[n-1]
					arr[n-1] = tmp
				} else {
					tmp := arr[0]
					arr[0] = arr[n-1]
					arr[n-1] = tmp
				}
			}
		}
	}
	helper(arr, len(arr))
	return res
}

func isPrime(n int) bool {
	if n == 1 {
		return false
	}
	for i := 2; i*i <= n; i++ {
		if n%i == 0 {
			return false
		}
	}
	return true
}

func divisor(n int) (res []int) {
	for i := 1; i*i <= n; i++ {
		if n%i == 0 {
			res = append(res, i)
			if i*i != n {
				res = append(res, n/i)
			}
		}
	}
	sort.Ints(res)
	return
}

/*-------------------init-------------------*/

const (
	INF = 1000000000000000000
	MOD = 1e9 + 7
)

var (
	readString func() string
)

func init() {
	readString = newReadString(os.Stdin)
}

/*-------------------inputs-------------------*/

func readi() int {
	return int(readi64())
}

func readi64() int64 {
	i, err := strconv.ParseInt(readString(), 0, 64)
	if err != nil {
		panic(err.Error())
	}
	return i
}

func readf() float64 {
	f, err := strconv.ParseFloat(readString(), 64)
	if err != nil {
		panic(err.Error())
	}
	return f
}

func newReadString(ior io.Reader) func() string {
	r := bufio.NewScanner(ior)
	r.Buffer(make([]byte, 1024), int(1e+11))
	r.Split(bufio.ScanWords)

	return func() string {
		if !r.Scan() {
			panic("Scan failed")
		}
		return r.Text()
	}
}
//  [go]
package main

import (
	"bufio"
	"fmt"
	"os"
	"strconv"
)

var sc = bufio.NewScanner((os.Stdin))

func nextLine() string {
	sc.Scan()
	return sc.Text()
}

func nextInt() int {
	l := nextLine()
	i, e := strconv.Atoi(l)
	if e != nil {
		panic(e)
	}
	return i
}

func main() {
	sc.Split(bufio.ScanWords)
	N, H := nextInt(), []int{}
	for i := 0; i < N; i++ {
		H = append(H, nextInt())
	}

	fmt.Printf("%d\n", ABC116C(N, H))
}

// ABC116C ...
func ABC116C(N int, H []int) int {
	res := 0

	c := []int{}
	for i := 0; i < len(H); i++ {
		c = append(c, 0)
	}

	l := 0
	for l != N-1 || c[N-1] < H[N-1] {
		for r := l; r < len(H); r++ {
			if H[r] > c[r] {
				c[r]++
			} else {
				break
			}
		}
		res++

		for i := l; i < len(H); i++ {
			if H[i] > c[i] || i == len(H)-1 {
				l = i
				break
			}
		}
	}

	return res
}
//  [go]
package main

import (
	"bufio"
	"fmt"
	"os"
	"strconv"
	"strings"
)

func water(l int, r int, h []int) []int {
	for i := l; i < r; i++ {
		h[i] -= 1
	}
	return h
}

func main() {
	var n int
	var s []string
	count := 0
	sc := bufio.NewScanner(os.Stdin)
	if sc.Scan() {
		nt := sc.Text()
		n, _ = strconv.Atoi(nt)
	}
	var h []int
	if sc.Scan() {
		s = strings.Split(sc.Text(), " ")
		for i := 0; i < len(s); i++ {
			hn, _ := strconv.Atoi(s[i])
			h = append(h, hn)
		}
	}

	index := 0
	for {
		l := -1
		r := len(h)
		for i := index; i < n; i++ {
			if l == -1 && h[i] != 0 {
				l = i
        index = i
				continue
			}
			if l != -1 && h[i] == 0 {
				r = i
			}
		}

		if l == -1 {
			break
		}
		h = water(l, r, h)
		count += 1
	}
	fmt.Print(count)
}
//  [go]
package main

import (
	"bufio"
	"fmt"
	"os"
	"strconv"
	"strings"
)

func water(l int, r int, h []int) []int {
	for i := l; i < r; i++ {
		h[i] -= 1
	}
	return h
}

func main() {
	var n int
	var s []string
	count := 0
	sc := bufio.NewScanner(os.Stdin)
	if sc.Scan() {
		nt := sc.Text()
		n, _ = strconv.Atoi(nt)
	}
	var h []int
	if sc.Scan() {
		s = strings.Split(sc.Text(), " ")
		for i := 0; i < len(s); i++ {
			hn, _ := strconv.Atoi(s[i])
			h = append(h, hn)
		}
	}

	for {
		l := -1
		r := len(h)
		for i := 0; i < n; i++ {
			if l == -1 && h[i] != 0 {
				l = i
				continue
			}
			if l != -1 && h[i] == 0 {
				r = i
			}
		}

		if l == -1 {
			break
		}
		h = water(l, r, h)
		count += 1
	}
	fmt.Print(count)
}
//  [ruby]
n = gets.to_i
hs = gets.split.map(&:to_i)

ans = hs[0]
(n - 1).times do |i|
  ans += hs[i + 1] - hs[i] if hs[i] <= hs[i + 1]
end

puts ans
//  [ruby]
=begin
－－－－－－－－－－－－－－
N = 数列の長さ
h = 花の高さの最終目標
ans = 操作回数
－－－－－－－－－－－－－－
1: 数列の先頭の値を取り出し 残った数列 - 先頭の値 を 配列が空になるまで繰り返す
  1.1: 先頭の値が 正の数 の場合は ans に加算し、操作を続ける (負の数の場合 ans への加算は行わない: 操作しすぎた数を戻している作業になる)
2: ans を出力する 
=end

N = gets.to_i;
h = gets.split.map(&:to_i);
ans = 0;

while h.empty? == false do
  a = h.shift;
  ans += a if a > 0;
  h.map!{|v| v - a};
end

p ans
//  [ruby]
n = gets.to_i
hs = gets.split.map(&:to_i)

ans = hs[0]
(n - 1).times do |i|
  l = hs[i]
  r = hs[i + 1]
  ans += r - l if l <= r
end

puts ans
//  [ruby]
n = gets.to_i
h = gets.split.map &:to_i
segs = [0..(n-1)]

cnt = 0

until segs.empty?
  seg = segs.pop
  
  min = h[seg.min_by { |i| h[i] }]
  cnt += 1 if min > 0
  
  i = seg.first
  seg.each do |j|
    h[j] -= min
    if h[j] == 0
      segs << (i..j-1) if i < j
      i = j+1
    end
  end
  if i < seg.last
    segs << (i..seg.last)
  end
end

p cnt
//  [ruby]
n = gets.to_i
h = gets.split.map(&:to_i)

ans = 0

while !h.count(0) != n
  prev = 0
  n.times do |i|
    if h[i] == 0 && i == 0
      prev += 1
      next
    elsif h[i] == 0 && h[i-1] == 0
      prev += 1
      next
    elsif h[i] == 0 && i!=0 && h[i-1] != 0
      ans += 1
      h[prev..(i-1)] = h[prev..(i-1)].map{|j| j-1}
      prev = i+1
      next
    elsif i == n-1
      ans += 1
      h[prev..i] = h[prev..i].map{|j| j-1}
      prev = 0
      next
    end
  end
end

puts ans
//  [ruby]
n = gets.to_i
h = gets.split.map(&:to_i)

ans = 0

while !h.all?(0)
  prev = 0
  n.times do |i|
    if h[i] == 0 && i == 0
      prev += 1
      next
    elsif h[i] == 0 && h[i-1] == 0
      prev += 1
      next
    elsif h[i] == 0 && i!=0 && h[i-1] != 0
      ans += 1
      h[prev..(i-1)] = h[prev..(i-1)].map{|j| j-1}
      prev = i+1
      next
    elsif i == n-1
      ans += 1
      h[prev..i] = h[prev..i].map{|j| j-1}
      prev = 0
      next
    end
  end
end

puts ans
//  [rust]
use std::io::*;
use std::str::FromStr;

pub fn read<T: FromStr>() -> T {
    let stdin = stdin();
    let stdin = stdin.lock();
    let token: String = stdin
        .bytes()
        .map(|c| c.expect("failed to read char") as char)
        .skip_while(|c| c.is_whitespace())
        .take_while(|c| !c.is_whitespace())
        .collect();
    token.parse().ok().expect("failed to parse token")
}

fn main() {
    let n: usize = read();
    let mut prev = 0;
    let mut ans = 0;

    for i in 0..n {
        let ni = read();
        if ni > prev {
            ans += (ni - prev);
        }
        prev = ni;
    }
    println!("{}", ans);
}
//  [rust]
#![allow(unused_imports)]

macro_rules! input {
    (source = $s:expr, $($r:tt)*) => {
        let mut iter = $s.split_whitespace();
        input_inner!{iter, $($r)*}
    };
    ($($r:tt)*) => {
        let s = {
            use std::io::Read;
            let mut s = String::new();
            std::io::stdin().read_to_string(&mut s).unwrap();
            s
        };
        let mut iter = s.split_whitespace();
        input_inner!{iter, $($r)*}
    };
}

macro_rules! input_inner {
    ($iter:expr) => {};
    ($iter:expr, ) => {};

    ($iter:expr, $var:ident : $t:tt $($r:tt)*) => {
        let $var = read_value!($iter, $t);
        input_inner!{$iter $($r)*}
    };
}

macro_rules! read_value {
    ($iter:expr, ( $($t:tt),* )) => {
        ( $(read_value!($iter, $t)),* )
    };

    ($iter:expr, [ $t:tt ; $len:expr ]) => {
        (0..$len).map(|_| read_value!($iter, $t)).collect::<Vec<_>>()
    };

    ($iter:expr, chars) => {
        read_value!($iter, String).chars().collect::<Vec<char>>()
    };

    ($iter:expr, usize1) => {
        read_value!($iter, usize) - 1
    };

    ($iter:expr, $t:ty) => {
        $iter.next().unwrap().parse::<$t>().expect("Parse error")
    };
}

use std::{i32, i64, u32, u64, usize, f64};
use std::cmp::{max, min, Ordering};
use std::collections::*;
use std::io::{stdout, Write, BufWriter};
use std::mem::{swap};

fn main() {
    input! {
        n: usize,
        hs: [usize; n],
    }
    let mut ans = 0usize;
    solve(&mut ans, &hs);
    println!("{}", ans);
}

fn solve(ans: &mut usize, hs: &[usize]) {
    match hs.iter().min() {
        Some(&m) => {
            if hs.iter().all(|h| *h == 0) {
                return;
            }
            *ans += m;
            let hss: Vec<_> = hs.iter().map(|h| h - m).collect();
            for hs in hss.split(|&h| h == 0) {
                solve(ans, hs);
            }
        },
        None => { return; },
    }
}
//  [rust]
#[allow(dead_code)]
fn main() {
    let n = i::u();
    let h = i::uv(n);

    let mut ans = 0;
    let mut current = vec![0; n];
    for _ in 0..100 {
        let mut c = 0;
        for i in 0..n {
            if current[i] == h[i] {
                if c == 0 {
                    continue;
                }
                c = 0;
                ans += 1;
            } else {
                c += 1;
                current[i] += 1;
            }
        }
        if c > 0 {
            ans += 1;
        }
    }
    println!("{}", ans);
}

#[allow(unused_imports)]
use std::cmp::*;
#[allow(unused_imports)]
use std::collections::{HashMap, HashSet, VecDeque};
#[allow(unused_imports)]
use std::io::*;
#[allow(unused_imports)]
use std::num::*;
#[allow(unused_imports)]
use std::str::*;

#[allow(dead_code)]
mod i {
    use super::*;

    pub fn read<T: FromStr>() -> T {
        stdin()
            .bytes()
            .map(|c| c.unwrap() as char)
            .skip_while(|c| c.is_whitespace())
            .take_while(|c| !c.is_whitespace())
            .collect::<String>()
            .parse::<T>()
            .ok()
            .unwrap()
    }

    pub fn str() -> String {
        read()
    }

    pub fn s() -> Vec<char> {
        str().chars().collect()
    }

    pub fn i() -> i64 {
        read()
    }

    pub fn u() -> usize {
        read()
    }

    pub fn u2() -> (usize, usize) {
        (read(), read())
    }

    pub fn u3() -> (usize, usize, usize) {
        (read(), read(), read())
    }

    pub fn f() -> f64 {
        read()
    }

    pub fn c() -> char {
        read::<String>().pop().unwrap()
    }

    pub fn iv(n: usize) -> Vec<i64> {
        (0..n).map(|_| i()).collect()
    }

    pub fn iv2(n: usize) -> Vec<(i64, i64)> {
        (0..n).map(|_| iv(2)).map(|a| (a[0], a[1])).collect()
    }

    pub fn uv(n: usize) -> Vec<usize> {
        (0..n).map(|_| u()).collect()
    }

    pub fn uv2(n: usize) -> Vec<(usize, usize)> {
        (0..n).map(|_| uv(2)).map(|a| (a[0], a[1])).collect()
    }

    pub fn uv3(n: usize) -> Vec<(usize, usize, usize)> {
        (0..n).map(|_| uv(3)).map(|a| (a[0], a[1], a[2])).collect()
    }

    pub fn fv(n: usize) -> Vec<f64> {
        (0..n).map(|_| f()).collect()
    }

    pub fn cmap(h: usize) -> Vec<Vec<char>> {
        (0..h).map(|_| s()).collect()
    }
}