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) || (b == c && c == d) {
  print("Yes")
} else {
  print("No")
}


let i=readLine()!.characters.map{$0};print((i[0]==i[1]||i[2]==i[3])&&i[1]==i[2] ?"Yes":"No")


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())


let i=readLine()!.characters.map{$0};print(i[1]==i[2]&&i[0]==i[1]||i[2]==i[3] ?"Yes":"No")


let i=readLine()!.characters.map{$0};print(i[0]==i[1]||i[2]==i[3]&&i[1]==i[2] ?"Yes":"No")


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")
}


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')


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()


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();
}


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();
}


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();
}


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);


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)


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)


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)


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)


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)


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)


import java.io.IOException;
import java.util.NoSuchElementException;

import java.io.InputStream;

import java.io.PrintWriter;

import java.util.Arrays;

@SuppressWarnings("unchecked")
public class Main {
    public static void main(String[] args) throws IOException {
        PrintWriter out = new PrintWriter(System.out);

        final int N = nextInt();

        int[] h = new int[N];
        int[] after = new int[N];

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

        boolean[] done = new boolean[N];

        int cnt = 0;

        for (int i = 0; i < N; i++) {
            if (h[i] == 0) {
                done[i] = true;
                cnt++;
            }
        }

        boolean flg = true;

        int ans = 0;

        while (flg) {
            if (cnt == N) break;

            ans++;

            boolean on = false;
            boolean change = false;

            for(int i = 0; i < N; i++) {
                if (!done[i]) {
                    on = true;
                    if (change) {
                        ans++;
                        change = false;
                    }
                    after[i]++;
                    if (after[i] == h[i]) {
                        done[i] = true;
                        cnt++;
                    }
                } else {
                    if (on) {
                        change = true;
                        on = false;
                    }
                }
            }
        }

        out.println(ans);

        out.flush();
    }

    // FastScanner start
    static final InputStream in = System.in;
    static final byte[] buffer = new byte[1024];
    static int ptr = 0;
    static int buflen = 0;
    static boolean hasNextByte() {
        if (ptr < buflen) {
            return true;
        } else {
            ptr = 0;
            try {
                buflen = in.read(buffer);
            } catch (IOException e) {
                e.printStackTrace();
            }
            if (buflen <= 0) {
                return false;
            }
        }
        return true;
    }
    static int readByte() {
        if (hasNextByte()) return buffer[ptr++];
        else return -1;
    }
    static boolean isPrintableChar(int c) {
        return 33 <= c && c <= 126;
    }
    static boolean hasNext() {
        while (hasNextByte() && !isPrintableChar(buffer[ptr])) ptr++;
        return hasNextByte();
    }
    static String next() {
        if (!hasNext()) throw new NoSuchElementException();
        StringBuilder sb = new StringBuilder();
        int b = readByte();
        while (isPrintableChar(b)) {
            sb.appendCodePoint(b);
            b = readByte();
        }
        return sb.toString();
    }
    static long nextLong() {
        if (!hasNext()) throw new NoSuchElementException();
        long n = 0;
        boolean minus = false;
        int b = readByte();
        if (b == '-') {
            minus = true;
            b = readByte();
        }
        if (b < '0' || '9' < b) {
            throw new NumberFormatException();
        }
        while (true) {
            if ('0' <= b && b <= '9') {
                n *= 10;
                n += b - '0';
            } else if(b == -1 || !isPrintableChar(b)) {
                return minus ? -n : n;
            } else {
                throw new NumberFormatException();
            }
            b = readByte();
        }
    }
    static int nextInt() {
        long nl = nextLong();
        if (nl < Integer.MIN_VALUE || nl > Integer.MAX_VALUE)
            throw new NumberFormatException();
        return (int) nl;
    }
    static double nextDouble() {
        return Double.parseDouble(next());
    }
    // FastScanner end
}


import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.NoSuchElementException;

class FastScanner {
    private final InputStream in = System.in;
    private final byte[] buffer = new byte[1024];
    private int ptr = 0;
    private int buflen = 0;

    private boolean hasNextByte() {
        if (ptr < buflen) {
            return true;
        } else {
            ptr = 0;
            try {
                buflen = in.read(buffer);
            } catch (IOException e) {
                e.printStackTrace();
            }
            if (buflen <= 0) {
                return false;
            }
        }
        return true;
    }

    private int readByte() {
        if (hasNextByte())
            return buffer[ptr++];
        else
            return -1;
    }

    private static boolean isPrintableChar(int c) {
        return 33 <= c && c <= 126;
    }

    public boolean hasNext() {
        while (hasNextByte() && !isPrintableChar(buffer[ptr]))
            ptr++;
        return hasNextByte();
    }

    public String next() {
        if (!hasNext())
            throw new NoSuchElementException();
        StringBuilder sb = new StringBuilder();
        int b = readByte();
        while (isPrintableChar(b)) {
            sb.appendCodePoint(b);
            b = readByte();
        }
        return sb.toString();
    }

    public long nextLong() {
        if (!hasNext())
            throw new NoSuchElementException();
        long n = 0;
        boolean minus = false;
        int b = readByte();
        if (b == '-') {
            minus = true;
            b = readByte();
        }
        if (b < '0' || '9' < b) {
            throw new NumberFormatException();
        }
        while (true) {
            if ('0' <= b && b <= '9') {
                n *= 10;
                n += b - '0';
            } else if (b == -1 || !isPrintableChar(b)) {
                return minus ? -n : n;
            } else {
                throw new NumberFormatException();
            }
            b = readByte();
        }
    }

    public int nextInt() {
        long nl = nextLong();
        if (nl < Integer.MIN_VALUE || nl > Integer.MAX_VALUE)
            throw new NumberFormatException();
        return (int) nl;
    }

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

public class Main {
    static int MOD = 1000000007;

    static int C(int n, int r) {
        int num = 1;
        for (int i = 1; i <= r; i++) {
            num = num * (n - i + 1) / i;
        }
        return num;
    }

    public static int gcd(int a, int b) {
        return b == 0 ? a : gcd(b, a % b);
    }

    static long lcm(long a, long b) {
        long temp;
        long c = a;
        c *= b;
        while ((temp = a % b) != 0) {
            a = b;
            b = temp;
        }
        return (long) (c / b);
    }

    static long f(long n, Map<Long, Long> map) {
        if (n < 2)
            return 1;
        else if (map.containsKey(n)) {
            return map.get(n);
        } else {
            map.put(n, n * f(n - 2, map));
            return map.get(n);
        }

    }

    public static long factorial(long n) {
        return n <= 0 ? 1 : n * factorial(n - 1);
    }

    private static long calcLCM(long val1, long val2) {
        long maxValue = Math.max(val1, val2);
        long minValue = Math.min(val1, val2);
        long val3 = maxValue * minValue;

        if (minValue == 0)
            return maxValue;

        long temp;
        while ((temp = maxValue % minValue) != 0) {
            maxValue = minValue;
            minValue = temp;
        }

        return (long) (val3 / minValue);
    }

    static String nextPermutation(String s) {
        ArrayList<Character> list = new ArrayList<>();
        for (int i = 0; i < s.length(); i++)
            list.add(s.charAt(i));

        int pivotPos = -1;
        char pivot = 0;
        for (int i = list.size() - 2; i >= 0; i--) {
            if (list.get(i) < list.get(i + 1)) {
                pivotPos = i;
                pivot = list.get(i);
                break;
            }
        }

        if (pivotPos == -1 && pivot == 0)
            return "Final";

        int L = pivotPos + 1, R = list.size() - 1;
        int minPos = -1;
        char min = Character.MAX_VALUE;
        for (int i = R; i >= L; i--) {
            if (pivot < list.get(i)) {
                if (list.get(i) < min) {
                    min = list.get(i);
                    minPos = i;
                }
            }
        }

        Collections.swap(list, pivotPos, minPos);
        Collections.sort(list.subList(L, R + 1));

        StringBuilder sb = new StringBuilder();
        for (int i = 0; i < list.size(); i++)
            sb.append(list.get(i));

        return sb.toString();

    }

    public List<String> permutation(List<String> list, String target, String ans) {
        if (target.length() <= 1) {
            list.add(ans + target);
        } else {
            for (int i = 0; i < target.length(); i++) {
                permutation(list, target.substring(0, i) + target.substring(i + 1), ans + target.charAt(i));
            }
        }
        return list;
    }

    public static int lowerbound(int[] a, int key) {
        if (a[a.length - 1] < key)
            return a.length;
        int lb = 0, ub = a.length - 1, mid;
        do {
            mid = (ub + lb) / 2;
            if (a[mid] < key)
                lb = mid + 1;
            else
                ub = mid;
        } while (lb < ub);
        return ub;
    }

    public static int upperbound(int[] a, int key) {
        if (a[a.length - 1] <= key)
            return a.length;
        int lb = 0, ub = a.length - 1, mid;
        do {
            mid = (ub + lb) / 2;
            if (a[mid] <= key)
                lb = mid + 1;
            else
                ub = mid;
        } while (lb < ub);
        return ub;
    }

    public static int count(int[] a, int key) {
        return upperbound(a, key) - lowerbound(a, key);
    }

    public static void main(String[] args) {
        FastScanner fs = new FastScanner();
        int n = fs.nextInt();
        int[] h = new int[n];
        int count = 0;
        for (int i = 0; i < n; i++) {
            h[i] = fs.nextInt();
            if (i == 0)
                count += 0 + h[i];
            else count += Math.max(0, h[i] - h[i - 1]);
        }
        System.out.println(count);
    }

}


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;
	}

}


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);
    }
}


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();
    }
}


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;
	    }
	}
}


#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;
}


//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;
}


#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;
}


#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;
}


#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;
}


#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;
}


#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;

}


#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);
}


#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;
}


#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;
}


#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;
}


#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;
}


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);
}


"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'));


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
`);


"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"));


"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"));


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'))


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)
}


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)
}


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()
	}
}


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
}


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)
}


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)
}


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


=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


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


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


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


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


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);
}


#![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; },
    }
}


#[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()
    }
}


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

fn flatten_get(s: &mut [u32]) -> u32 {
    if s.len() == 0 {
        return 0;
    }
    let (index, min) =
        s.iter()
            .enumerate()
            .fold((0, std::u32::MAX), |(acc_index, acc), (index, v)| {
                if acc > *v {
                    (index, *v)
                } else {
                    (acc_index, acc)
                }
            });
    s.iter_mut().for_each(|v| *v -= min);
    let (left, right) = s.split_at_mut(index);
    let mut sum = min;
    sum += flatten_get(left);
    if right.len() > 0 {
        sum += flatten_get(&mut right[1..]);
    }
    sum
}

fn main() {
    input! {
        n: usize,
        hs: [u32; n],
    }

    let ans = flatten_get(&mut hs);
    println!("{}", ans);
}


#![allow(unused_parens)]
#![allow(unused_imports)]
#![allow(non_upper_case_globals)]
#![allow(non_snake_case)]
#![allow(unused_mut)]
#![allow(unused_variables)]
#![allow(dead_code)]

#[allow(unused_macros)]
macro_rules! invec {
    ( $ t : ty ) => {{
        let mut s = String::new();
        match std::io::stdin().read_line(&mut s) {
            Ok(0) => Vec::<$t>::new(),
            Ok(n) => s
                .trim()
                .split_whitespace()
                .map(|s| s.parse::<$t>().unwrap())
                .collect::<Vec<$t>>(),
            Err(_) => Vec::<$t>::new(),
        }
    }};
}

#[allow(unused_macros)]
macro_rules! get {
      ($t:ty) => {
          {
              let mut line: String = String::new();
              std::io::stdin().read_line(&mut line).unwrap();
              line.trim().parse::<$t>().unwrap()
          }
      };
      ($($t:ty),*) => {
          {
              let mut line: String = String::new();
              std::io::stdin().read_line(&mut line).unwrap();
              let mut iter = line.split_whitespace();
              (
                  $(iter.next().unwrap().parse::<$t>().unwrap(),)*
              )
          }
      };
      ($t:ty; $n:expr) => {
          (0..$n).map(|_|
              get!($t)
          ).collect::<Vec<_>>()
      };
      ($($t:ty),*; $n:expr) => {
          (0..$n).map(|_|
              get!($($t),*)
          ).collect::<Vec<_>>()
      };
      ($t:ty ;;) => {
          {
              let mut line: String = String::new();
              std::io::stdin().read_line(&mut line).unwrap();
              line.split_whitespace()
                  .map(|t| t.parse::<$t>().unwrap())
                  .collect::<Vec<_>>()
          }
      };
      ($t:ty ;; $n:expr) => {
          (0..$n).map(|_| get!($t ;;)).collect::<Vec<_>>()
      };
}

#[allow(unused_macros)]
macro_rules! input {
    (source = $s:expr, $($r:tt)*) => {
        let mut iter = $s.split_whitespace();
        input_inner!{iter, $($r)*}
    };
    ($($r:tt)*) => {
        let mut 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)*}
    };
    ($iter:expr, mut $var:ident : $t:tt $($r:tt)*) => {
        let mut $var = read_value!($iter, $t);
        input_inner!{$iter $($r)*}
    };
}

#[allow(unused_macros)]
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<_>>()
    };

    ($next:expr, [$t:tt]) => {
        {
            let len = read_value!($next, usize);
            (0..len).map(|_| read_value!($next, $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")
    };
}

#[allow(unused_macros)]
#[cfg(debug_assertions)]
macro_rules! mydbg {
    //($arg:expr) => (dbg!($arg))
    //($arg:expr) => (println!("{:?}",$arg));
      ($($a:expr),*) => {
          eprintln!(concat!($(stringify!($a), " = {:?}, "),*), $($a),*);
      }
}
#[cfg(not(debug_assertions))]
macro_rules! mydbg {
    ($($arg:expr),*) => {};
}

macro_rules! echo {
    ($($a:expr),*) => {
          $(println!("{}",$a))*
      }
}

use std::cmp::*;
use std::collections::*;
use std::ops::{Add, Div, Mul, Sub};

#[allow(dead_code)]
static INF_I64: i64 = 92233720368547758;
#[allow(dead_code)]
static INF_I32: i32 = 21474836;
#[allow(dead_code)]
static INF_USIZE: usize = 18446744073709551;
#[allow(dead_code)]
static M_O_D: usize = 1000000007;
#[allow(dead_code)]
static PAI: f64 = 3.1415926535897932;

trait IteratorExt: Iterator {
    fn toVec(self) -> Vec<Self::Item>;
}

impl<T: Iterator> IteratorExt for T {
    fn toVec(self) -> Vec<Self::Item> {
        self.collect()
    }
}

trait CharExt {
    fn toNum(&self) -> usize;
    fn toAlphabetIndex(&self) -> usize;
    fn toNumIndex(&self) -> usize;
}
impl CharExt for char {
    fn toNum(&self) -> usize {
        return *self as usize;
    }
    fn toAlphabetIndex(&self) -> usize {
        return self.toNum() - 'a' as usize;
    }
    fn toNumIndex(&self) -> usize {
        return self.toNum() - '0' as usize;
    }
}

trait VectorExt {
    fn joinToString(&self, s: &str) -> String;
}
impl<T: ToString> VectorExt for Vec<T> {
    fn joinToString(&self, s: &str) -> String {
        return self
            .iter()
            .map(|x| x.to_string())
            .collect::<Vec<_>>()
            .join(s);
    }
}

trait StringExt {
    fn get_reverse(&self) -> String;
}
impl StringExt for String {
    fn get_reverse(&self) -> String {
        self.chars().rev().collect::<String>()
    }
}

trait UsizeExt {
    fn pow(&self, n: usize) -> usize;
}
impl UsizeExt for usize {
    fn pow(&self, n: usize) -> usize {
        return ((*self as u64).pow(n as u32)) as usize;
    }
}

fn main() {
    input! {
       n: usize,
       mut h:[usize;n],
    }

    let mut ans: usize = 0;
    let mut h2 = vec![];
    h2.push(h[0]);
    for i in 1..n {
        if h[i - 1] != h[i] {
            h2.push(h[i]);
        }
    }
    mydbg!(h2);
    loop {
        let a = h2.iter().filter(|&x| *x > 0).min();
        if a.is_none() {
            break;
        }
        let b = *a.unwrap();

        let i = h2.iter().position(|&x| x == b).unwrap();
        for j in i..h2.len() {
            if h2[j] >= b {
                h2[j] -= b;
            } else {
                break;
            }
        }
        for j in (0..i).rev() {
            if h2[j] >= b {
                h2[j] -= b;
            } else {
                break;
            }
        }
        ans += b;
    }

    echo!(ans);
}


#[allow(dead_code)]
fn read<T: std::str::FromStr>() -> T {
    let mut s = String::new();
    std::io::stdin().read_line(&mut s).ok();
    s.trim().parse().ok().unwrap()
}
#[allow(dead_code)]
fn read_vec<T: std::str::FromStr>() -> Vec<T> {
    read::<String>()
        .split_whitespace()
        .map(|e| e.parse().ok().unwrap())
        .collect()
}
#[allow(dead_code)]
fn read_vec2<T: std::str::FromStr>(n: u32) -> Vec<Vec<T>> {
    (0..n).map(|_| read_vec()).collect()
}
#[allow(dead_code)]
fn yn(result: bool) {
    if result {
        println!("Yes");
    } else {
        println!("No");
    }
}

fn main() {
    let n = read::<usize>();
    let v = read_vec::<u32>();

    if v.len() == 1 {
        println!("{}", v[0]);
        return;
    }

    let mut count = 0;
    for i in 0..n {
        if i == 0 {
            if v[i] > 0 && v[i] >= v[i + 1] {
                count += v[i];
            }
        } else if i == n-1 {
            if v[i] > v[i-1] {
                count += v[i];
            }
        } else {
            if v[i] > v[i-1] && v[i] >= v[i+1] {
                count += v[i];
            } else if v[i] < v[i-1] && v[i] <= v[i+1] {
                count -= v[i];
            }
        }
    }
    println!("{}", count);
}


import Foundation

#if swift(>=4.0)
extension String {
    func split(by separator: String) -> [String] {
        return self.components(separatedBy: separator)
    }
    func toArray() -> [String] {
        return self.map{String($0)}
    }
}
func exponentiate(_ lhs: Int, _ rhs: Int) -> Int {
    return (0..<rhs).reduce(1){i,_ in i*lhs}
}
#else
extension String {
    func split(by separator: String) -> [String] {
        return self.componentsSeparatedByString(separator)
    }
    var count: Int {
        return self.characters.count
    }
    func toArray() -> [String] {
        return self.characters.map{String($0)}
    }
    func uppercased() -> String {
        return self.uppercaseString
    }
    func lowercased() -> String {
        return self.lowercaseString
    }
}
//extension Array where Element == String {
//    func joined(separator separator: String) -> String {
//        return self.joinWithSeparator(separator)
//    }
//}
extension Array where Element: Comparable {
    func max() -> Element? {
        return self.maxElement()
    }
    func min() -> Element? {
        return self.minElement()
    }
    func sorted() -> Array {
        return self.sort()
    }
    func reversed() -> Array {
        return self.reverse()
    }
//    func enumerated() -> [(Int, Element)] {
//        return self.enumerate()
//    }
    mutating func sort() {
        self.sortInPlace()
    }
}
extension Array {
    init(repeating: Element, count: Int) {
        self.init(count: count, repeatedValue: repeating)
    }
}
func stride<T: Strideable>(from start: T, to end: T, by stride: T.Stride) -> StrideTo<T> {
    return start.stride(to: end, by: stride)
}
func exponentiate(lhs: Int, _ rhs: Int) -> Int {
    return (0..<rhs).reduce(1){i,_ in i*lhs}
}
#endif
func readInt() -> Int? {
    return Int(readLine()!)
}
func readStringSplit(by separator: String) -> [String] {
    return readLine()!.split(by: separator)
}
func readIntSplit(by separator: String) -> [Int] {
    return readLine()!.split(by: separator).map{Int($0)!}
}

/*************** テストスペース ***************/

/*************** メインプログラム ***************/

let N = readInt()!
var flowers = readIntSplit(by: " ")
var ans = 0
while flowers.max()! > 0 {
    var flag = false
    for i in 0..<N {
        if flowers[i] > 0 {
            flowers[i] -= 1
            if !flag {
                ans += 1
                flag = true
            }
        } else {
            flag = false
        }
    }
}
print(ans)


// 🐋💭
import Foundation

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

func readInt() -> Int {
    return Int(readLine()!)!
}

func readDoubles () -> [Double] {
    return readLine()!.split(separator: " ").map { Double($0)! }
}

func readDouble() -> Double{
    return Double(readLine()!)!
}
///最大公約数を返す
func gcd(_ m:Int, _ n:Int) -> Int {
    if n == 0 {return m}
    return gcd(n, m % n)
}
///最小公倍数を返す
func lcm(_ m:Int, _ n:Int) -> Int {
    return m * n / gcd(m, n)
}

///素数判定(試し割り)
func isPrime(_ x:Int) -> Bool {
    if x <= 1 || x % 2 == 0 { return false }
    if x == 2 { return true }
    for i in stride(from: 3, to: Int(ceil(sqrt(Double(x)))), by: 2){
        if x % i == 0 {
            return false
        }
    }
    return true
}

//https://program-life.com/669
///実行速度の計測
func exectionTime(action: () -> Void) {
    let startDate = Date()
    action()
    let endDate = Date()
    print(endDate.timeIntervalSince(startDate))
}

// https://melheaven.hatenadiary.jp/entry/atcoder144
///約数の配列を返す
func makeDivisors(_ n:Int) -> [Int] {
    var divisors = [Int]()
    for i in 1..<Int(pow(Double(n), 0.5)) + 1 {
        if n % i == 0{
            divisors.append(i + n / i)
        }
    }

    return divisors
}

//https://riptutorial.com/ja/swift/example/14738/インデックスを知らずに配列から要素を削除する
extension Array where Element: Equatable {

    mutating func remove(_ element: Element) {
        _ = firstIndex(of: element).flatMap {
            self.remove(at: $0)
        }
    }
}

func binarySearch(rifgt:Int, key:Int, ary:[String]) -> Int{
    var left = 0
    var right = rifgt

    while abs(right - left) > 1 {
        let mid = left + (right - left) / 2

        if Int(ary[mid])! < key {
            left = mid

        } else {
            right = mid
        }
    }
    return left
}

func arrangement (prev:String, ary:[String], returnVal:[String]) -> [String] {
    var returnVal = returnVal
    if ary.count == 0 {
        returnVal.append(prev)
        return returnVal
    }

    for s in ary {
        let wprev = prev + s
        var wary = ary
        wary.remove(s)
        returnVal = arrangement(prev: wprev, ary: wary, returnVal: returnVal)
    }
    return returnVal
}

func main() {
    let n = readInt()
    var flowerH = readInts()
    //＿＿＿＿＿＿＿＿＿＿＿＿＿＿＿＿＿ここまで入力

    var left = 0
    var right = 1
    var ans = 0
    while right <= flowerH.count && left < n{
        while right < n && flowerH[right - 1] <= flowerH[right] {
            right += 1
        }
        while left < n && flowerH[left] < 1 {
            left += 1
        }
        for i in left..<right {
            flowerH[i] -= 1
        }

        ans += left == right ? 0: 1
    }
    print(ans)
}
main()


// 🐋💭
import Foundation

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

func readInt() -> Int {
    return Int(readLine()!)!
}

func readDoubles () -> [Double] {
    return readLine()!.split(separator: " ").map { Double($0)! }
}

func readDouble() -> Double{
    return Double(readLine()!)!
}
///最大公約数を返す
func gcd(_ m:Int, _ n:Int) -> Int {
    if n == 0 {return m}
    return gcd(n, m % n)
}
///最小公倍数を返す
func lcm(_ m:Int, _ n:Int) -> Int {
    return m * n / gcd(m, n)
}

///素数判定(試し割り)
func isPrime(_ x:Int) -> Bool {
    if x <= 1 || x % 2 == 0 { return false }
    if x == 2 { return true }
    for i in stride(from: 3, to: Int(ceil(sqrt(Double(x)))), by: 2){
        if x % i == 0 {
            return false
        }
    }
    return true
}

//https://program-life.com/669
///実行速度の計測
func exectionTime(action: () -> Void) {
    let startDate = Date()
    action()
    let endDate = Date()
    print(endDate.timeIntervalSince(startDate))
}

// https://melheaven.hatenadiary.jp/entry/atcoder144
///約数の配列を返す
func makeDivisors(_ n:Int) -> [Int] {
    var divisors = [Int]()
    for i in 1..<Int(pow(Double(n), 0.5)) + 1 {
        if n % i == 0{
            divisors.append(i + n / i)
        }
    }

    return divisors
}

//https://riptutorial.com/ja/swift/example/14738/インデックスを知らずに配列から要素を削除する
extension Array where Element: Equatable {

    mutating func remove(_ element: Element) {
        _ = firstIndex(of: element).flatMap {
            self.remove(at: $0)
        }
    }
}

func binarySearch(rifgt:Int, key:Int, ary:[String]) -> Int{
    var left = 0
    var right = rifgt

    while abs(right - left) > 1 {
        let mid = left + (right - left) / 2

        if Int(ary[mid])! < key {
            left = mid

        } else {
            right = mid
        }
    }
    return left
}

func arrangement (prev:String, ary:[String], returnVal:[String]) -> [String] {
    var returnVal = returnVal
    if ary.count == 0 {
        returnVal.append(prev)
        return returnVal
    }

    for s in ary {
        let wprev = prev + s
        var wary = ary
        wary.remove(s)
        returnVal = arrangement(prev: wprev, ary: wary, returnVal: returnVal)
    }
    return returnVal
}

func main() {
    let n = readInt()
    var flowerH = readInts()
    //＿＿＿＿＿＿＿＿＿＿＿＿＿＿＿＿＿ここまで入力

    var left = 0
    var right = 1
    var ans = 0
    while right <= flowerH.count && left < n{
        while right < n && flowerH[right - 1] <= flowerH[right] {
            right += 1
        }
        for i in left..<right {
            flowerH[i] -= 1
        }
        while left < n && flowerH[left] < 1 {
            left += 1
        }
        ans += 1
    }
    print(ans)
}
main()


const input=require('fs').readFileSync('/dev/stdin','utf8').split(/[\s]/);let input_i=-1;const tn=():number=>{input_i++;return Number(input[input_i])};const tnn=(n:number):number[]=>{const a=[];for(let i=0;i<n;i++){a.push(tn())}return a};const ts=():string=>{input_i++;return String(input[input_i])};const tss=(n:number):string[]=>{const a=[];for(let i=0;i<n;i++){a.push(ts())}return a};const to=(...arg)=>{console.log(...arg)};const abs=(a)=>{return Math.abs(a)};const min=(...a)=>{return Math.min(...a)};const max=(...a)=>{return Math.max(...a)};const floor=(a)=>{return Math.floor(a)};const ceil=(a)=>{return Math.ceil(a)};const asc=(ar:number[])=>{const t=[...ar];return ar.sort((a,b)=>{return a-b})};const desc=(ar:number[])=>{const t=[...ar];return t.sort((a,b)=>{return b-a})};const sw=(a,arr:any[],op:'=='|'>='|'>'|'<='|'<'='==')=>{for(let i=0;i<arr.length-1;i+=2){if(eval(a+op+arr[i])){return arr[i+1]}}return arr[arr.length-1]};const near=(n:number,arr:number[]):number=>{let ne=arr[0],ni=0;for(let i=1;i<arr.length;i++){if(Math.abs(n-ne)>Math.abs(n-arr[i])){ne=arr[i];ni=i}}return ni};const deduplicate=(a:any[]):any[]=>{return Array.from(new Set(a))};const gcd=(x,y)=>{while(y){[x,y]=[y,x%y]}return x};const sum=(arr)=>{return arr.reduce((a,b)=>a+b);};const isPrime=(n:number):boolean=>{if(n<2)return false;const suq=Math.sqrt(n);for(let i=2;i<=suq;i++){if(n%i==0){return false;}}return true;};
const main=()=>{
  let n=tn(),ar=tnn(n),ans=ar[0]
  for(let i=1;i<n;i++){
    if(ar[i-1]<ar[i]){
      ans+=ar[i]-ar[i-1]
    }
  }
  to(ans)
}
main()


const stdin = require('fs').readFileSync('/dev/stdin', 'utf8').trim()

const n = Number(stdin.split('\n')[0])
const h = stdin
  .split('\n')[1]
  .split(' ')
  .map(Number)

const ans = () => {
  let current = []

  for (let i = 0; i < n; i++) {
    current.push(0)
  }

  // 高さが足りないものを全てグループ化する
  // グループ化したものをすべて1増やす
  // 足りないものがなくなるまで繰り返す

  let count = 0
  while (1) {
    let head = -1
    let tail = -1

    // グループの始点と終点を探す
    for (let i = 0; i < n; i++) {
      if (head === -1 && current[i] < h[i]) {
        head = i
      }

      if (head > -1 && current[i] >= h[i]) {
        tail = i
        break
      }
    }

    // 終了条件
    if (head === -1) {
      return count
    }

    if (tail === -1) {
      tail = n
    }

    for (let i = head; i < tail; i++) {
      current[i] += 1
    }

    count++
  }
}

console.log(ans())


const solve = (input) => {
  const [n, hlist] = input.split("\n")
  const _hs = hlist.split(" ").map(Number)
  const hs = _hs.reduce((curr, next, i) => {
    if (_hs[i - 1] && _hs[i - 1] === _hs[i]) {
      return curr
    }
    return [...curr, next]
  }, [])
  let peaks = []
  hs.map((h, i, arr) => {
    const before = arr[i - 1] || 0
    const after = arr[i + 1] || 0
    // console.log(before, arr[i], after)
    if (arr[i] > before && arr[i] > after) {
      peaks.push(i)
    }
  })
  const pAndE = peaks.map((p) => {
    // let c = hs[p]
    for (i = p; i < hs.length; i++) {
      if (hs[i] < hs[i + 1]) {
        return {
          peak: p,
          peakValue: hs[p],
          edge: i,
          edgeValue: hs[i]
        }
      }
    }
    return {
      peak: p,
      peakValue: hs[p]
    }
  })
  let num = 0
  pAndE.map((p, j) => {
    num += p.peakValue
    if (j > 0) {
      const before = pAndE[j - 1]
      num -= before.edgeValue
    }
  })

  return num
}

if (process.env.NODE_ENV === "test") {
  module.exports = (input) => solve(input.trim())
} else {
  const input = require("fs").readFileSync("/dev/stdin", "utf8")
  console.log(solve(input.trim()))
}


const input=require('fs').readFileSync('/dev/stdin','utf8').split(/[\s]/);let input_i=-1;const tn=():number=>{input_i++;return Number(input[input_i])};const tnn=(n:number):number[]=>{const a=[];for(let i=0;i<n;i++){a.push(tn())}return a};const ts=():string=>{input_i++;return String(input[input_i])};const tss=(n:number):string[]=>{const a=[];for(let i=0;i<n;i++){a.push(ts())}return a};const to=(...arg)=>{console.log(...arg)};const abs=(a)=>{return Math.abs(a)};const min=(...a)=>{return Math.min(...a)};const max=(...a)=>{return Math.max(...a)};const floor=(a)=>{return Math.floor(a)};const ceil=(a)=>{return Math.ceil(a)};const asc=(ar:number[])=>{const t=[...ar];return ar.sort((a,b)=>{return a-b})};const desc=(ar:number[])=>{const t=[...ar];return t.sort((a,b)=>{return b-a})};const sw=(a,arr:any[],op:'=='|'>='|'>'|'<='|'<'='==')=>{for(let i=0;i<arr.length-1;i+=2){if(eval(a+op+arr[i])){return arr[i+1]}}return arr[arr.length-1]};const near=(n:number,arr:number[]):number=>{let ne=arr[0],ni=0;for(let i=1;i<arr.length;i++){if(Math.abs(n-ne)>Math.abs(n-arr[i])){ne=arr[i];ni=i}}return ni};const deduplicate=(a:any[]):any[]=>{return Array.from(new Set(a))};const gcd=(x,y)=>{while(y){[x,y]=[y,x%y]}return x};const sum=(arr)=>{return arr.reduce((a,b)=>a+b);};const isPrime=(n:number):boolean=>{if(n<2)return false;const suq=Math.sqrt(n);for(let i=2;i<=suq;i++){if(n%i==0){return false;}}return true;};
const main=()=>{
  let n=tn(),ar=tnn(n),start=-1,c=Infinity,flowers=new Array(n),ans=0
  flowers.fill(0)
  let e=0
  while(!e){
    e=1
    for(let i=0;i<n;i++){
      if(ar[i]==0||i==n-1){
        if(start!=-1){
          if(i==n-1){
            c=min(...ar.slice(start,i+1))
            for(let j=start;j<i+1;j++){
              ar[j]-=c
            }
          }else{
            c=min(...ar.slice(start,i))
            for(let j=start;j<i;j++){
              ar[j]-=c
            }
          }
          ans+=c
        }
        start=-1
        continue
      }
      if(start==-1){
        start=i
        e=0
      }
    }
  }
  to(ans+ar[ar.length-1])
}
main()


function main(input) {
  input = input.trim().split("\n");
  const n = Number(input[0]);
  const hs = input[1].split(" ").map(n => Number(n));
  const arr = Array(n).fill(0);
  let result = 0;
  const func = (l, r) => {
    if (l < 0 || n <= l || r < 0 || n <= r || r < l) return;
	const min = Math.min(...arr.slice(l, r+1);
    const target = Math.min(...hs.slice(l, r+1));
    const dif = target - min;
    const minIndices = [];
    for (let i = l; i <= r; i++) {
      arr[i] += dif;
      if (hs[i] === target) minIndices.push(i);
    }
    result += dif
    let nextL = l;
    for (let i = 0; i < minIndices.length; i++) {
      const index = minIndices[i];
      func(nextL, index-1);
      nextL = index + 1;
      if (i === minIndices.length -1) {
        func(nextL, hs.length -1);
      }
    }
  }
  func(0, n-1);
  console.log(result);
}
main(require("fs").readFileSync("/dev/stdin", "utf8"));


function main(input: string): void {
  const s = Number(input);
  let n = s;
  // If a[i] === 4, then i+3 is the answer
  let step = 1;
  if (s === 1 || s === 2 || s === 4) {
    step = 0;
  }
  let fourHasAppeared = false;
  while (!fourHasAppeared) {
    if (n % 2) {
      n = n * 3 + 1;
    } else {
      n /= 2;
    }

    if (n === 4) {
      fourHasAppeared = true;
    }
    step += 1;
  }
  const ans = step + 3;
  console.log(ans);
}

import * as fs from 'fs';
main(fs.readFileSync('/dev/stdin', 'utf8'));


def main():
    n, k = map(int, input().split(" "))
    h = list(map(int, input().split(" ")))
    h.sort(reverse = True)
    print(sum(h[k:]))

if __name__ == "__main__":
    main()


import sys
input = sys.stdin.readline

def main():
    N, K = map(int, input().split())
    H = list(map(int, input().split()))
    assert N == len(H)
    H.sort(reverse=True)
    print(sum(H[K:]))

if __name__ == '__main__':
    main()


n, k = map(int,input().split())
h = list(map(int,input().split()))

h.sort(reverse = True)
t = 0

del h[0:k]

if len(h) == 0 :
    print(0)
else:
    t += sum(h)
    print(t)


h,k = map(int,input().split())
lst = list(map(int,input().split()))
lst.sort()
print(sum(lst[:len(lst)-k]))


nn, kk = list(map(int,input().split()))
hh = list(map(int,input().split()))
hh.sort()
print(sum(hh[0:nn-kk]))


nn, kk = list(map(int,input().split()))
hh = list(map(int,input().split()))

print(nn,kk,hh)

hh.sort()
print(hh[0:nn-1])
print(sum(hh[0:nn-kk]))


// Utilities
import java.io.*;
import java.util.*;

public class Main {
  static int N, K;
  static int[] h;
  static long res = 0;

  public static void main(String[] args) throws IOException {
    INPUT in = new INPUT(System.in);
    N = in.iscan(); K = in.iscan(); h = new int[N];
    for (int i = 0; i < N; i++) h[i] = in.iscan();
    Arrays.sort(h);
    for (int i = 0; i < N - K; i++) res += h[i];
    System.out.println(res);
  }

  private static class INPUT {

		private InputStream stream;
		private byte[] buf = new byte[1024];
		private int curChar, numChars;

		public INPUT (InputStream stream) {
			this.stream = stream;
		}

		public INPUT (String file) throws IOException {
			this.stream = new FileInputStream (file);
		}

		public int cscan () throws IOException {
			if (curChar >= numChars) {
				curChar = 0;
				numChars = stream.read (buf);
			}

			if (numChars == -1)
				return numChars;

			return buf[curChar++];
		}

		public int iscan () throws IOException {
			int c = cscan (), sgn = 1;

			while (space (c))
				c = cscan ();

			if (c == '-') {
				sgn = -1;
				c = cscan ();
			}

			int res = 0;

			do {
				res = (res << 1) + (res << 3);
				res += c - '0';
				c = cscan ();
			}
			while (!space (c));

			return res * sgn;
		}

		public String sscan () throws IOException {
			int c = cscan ();

			while (space (c))
				c = cscan ();

			StringBuilder res = new StringBuilder ();

			do {
				res.appendCodePoint (c);
				c = cscan ();
			}
			while (!space (c));

			return res.toString ();
		}

		public double dscan () throws IOException {
			int c = cscan (), sgn = 1;

			while (space (c))
				c = cscan ();

			if (c == '-') {
				sgn = -1;
				c = cscan ();
			}

			double res = 0;

			while (!space (c) && c != '.') {
				if (c == 'e' || c == 'E')
					return res * UTILITIES.fast_pow (10, iscan ());

				res *= 10;
				res += c - '0';
				c = cscan ();
			}

			if (c == '.') {
				c = cscan ();
				double m = 1;

				while (!space (c)) {
					if (c == 'e' || c == 'E')
						return res * UTILITIES.fast_pow (10, iscan ());

					m /= 10;
					res += (c - '0') * m;
					c = cscan ();
				}
			}

			return res * sgn;
		}

		public long lscan () throws IOException {
			int c = cscan (), sgn = 1;

			while (space (c))
				c = cscan ();

			if (c == '-') {
				sgn = -1;
				c = cscan ();
			}

			long res = 0;

			do {
				res = (res << 1) + (res << 3);
				res += c - '0';
				c = cscan ();
			}
			while (!space (c));

			return res * sgn;
		}

		public boolean space (int c) {
			return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1;
		}
	}

	public static class UTILITIES {

		static final double EPS = 10e-6;

		public static int lower_bound (int[] arr, int x) {
			int low = 0, high = arr.length, mid = -1;

			while (low < high) {
				mid = (low + high) / 2;

				if (arr[mid] >= x)
					high = mid;
				else
					low = mid + 1;
			}

			return low;
		}

		public static int upper_bound (int[] arr, int x) {
			int low = 0, high = arr.length, mid = -1;

			while (low < high) {
				mid = (low + high) / 2;

				if (arr[mid] > x)
					high = mid;
				else
					low = mid + 1;
			}

			return low;
		}

		public static int gcd (int a, int b) {
			return b == 0 ? a : gcd (b, a % b);
		}

		public static int lcm (int a, int b) {
			return a * b / gcd (a, b);
		}

		public static long fast_pow_mod (long b, long x, int mod) {
			if (x == 0) return 1;
			if (x == 1) return b;
			if (x % 2 == 0) return fast_pow_mod (b * b % mod, x / 2, mod) % mod;

			return b * fast_pow_mod (b * b % mod, x / 2, mod) % mod;
		}

		public static int fast_pow (int b, int x) {
			if (x == 0) return 1;
			if (x == 1) return b;
			if (x % 2 == 0) return fast_pow (b * b, x / 2);

			return b * fast_pow (b * b, x / 2);
		}

		public static long choose (long n, long k) {
			k = Math.min (k, n - k);
			long val = 1;

			for (int i = 0; i < k; ++i)
				val = val * (n - i) / (i + 1);

			return val;
		}

		public static long permute (int n, int k) {
			if (n < k) return 0;
			long val = 1;

			for (int i = 0; i < k; ++i)
				val = (val * (n - i));

			return val;
		}
	}
}


import java.io.OutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.util.Arrays;
import java.io.BufferedWriter;
import java.io.Writer;
import java.io.OutputStreamWriter;
import java.util.InputMismatchException;
import java.io.IOException;
import java.io.InputStream;

/**
 * Built using CHelper plug-in
 * Actual solution is at the top
 */
public class Main {
    public static void main(String[] args) {
        InputStream inputStream = System.in;
        OutputStream outputStream = System.out;
        InputReader in = new InputReader(inputStream);
        OutputWriter out = new OutputWriter(outputStream);
        CFennecVsMonster solver = new CFennecVsMonster();
        solver.solve(1, in, out);
        out.close();
    }

    static class CFennecVsMonster {
        public void solve(int testNumber, InputReader in, OutputWriter out) {
            int n = in.nextInt();
            int k = in.nextInt();
            int[] arr = new int[n];
            for (int i = 0; i < arr.length; ++i) {
                arr[i] = in.nextInt();
            }
            if (k >= n) {
                out.println(0);
                return;
            } else {
                Arrays.sort(arr);
                long sum = 0;
                for (int i = 0; i < (n - k); ++i) {
                    sum += arr[i];
                }
                out.println(sum);
            }
        }

    }

    static class InputReader {
        private InputStream stream;
        private byte[] buf = new byte[1024];
        private int curChar;
        private int numChars;
        private InputReader.SpaceCharFilter filter;

        public InputReader(InputStream stream) {
            this.stream = stream;
        }

        public int read() {
            if (numChars == -1) {
                throw new InputMismatchException();
            }
            if (curChar >= numChars) {
                curChar = 0;
                try {
                    numChars = stream.read(buf);
                } catch (IOException e) {
                    throw new InputMismatchException();
                }
                if (numChars <= 0) {
                    return -1;
                }
            }
            return buf[curChar++];
        }

        public int nextInt() {
            int c = read();
            while (isSpaceChar(c)) {
                c = read();
            }
            int sgn = 1;
            if (c == '-') {
                sgn = -1;
                c = read();
            }
            int res = 0;
            do {
                if (c < '0' || c > '9') {
                    throw new InputMismatchException();
                }
                res *= 10;
                res += c - '0';
                c = read();
            } while (!isSpaceChar(c));
            return res * sgn;
        }

        public boolean isSpaceChar(int c) {
            if (filter != null) {
                return filter.isSpaceChar(c);
            }
            return isWhitespace(c);
        }

        public static boolean isWhitespace(int c) {
            return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1;
        }

        public interface SpaceCharFilter {
            public boolean isSpaceChar(int ch);

        }

    }

    static class OutputWriter {
        private final PrintWriter writer;

        public OutputWriter(OutputStream outputStream) {
            writer = new PrintWriter(new BufferedWriter(new OutputStreamWriter(outputStream)));
        }

        public OutputWriter(Writer writer) {
            this.writer = new PrintWriter(writer);
        }

        public void close() {
            writer.close();
        }

        public void println(long i) {
            writer.println(i);
        }

        public void println(int i) {
            writer.println(i);
        }

    }
}


import java.util.*;
import java.io.*;
class Main {
    public static void main(String[] args) {
        FastScanner sc = new FastScanner();
        int N = sc.nextInt();
        int K = sc.nextInt();
        int[] a = new int[N];
        for(int i = 0; i<N; i++) a[i] = sc.nextInt();
        Arrays.sort(a);
        if(N-K<=0){
            p(0);
            return;
        }
        long sum = 0;
        for(int i = N-1-K; i>=0; i--) {
            sum += a[i];
        }
        p(sum);
    }
    public static <T> void p(T element) {
	System.out.println(element);
    }
    public static int min(int a, int b, int c) {
	int min = Math.min(a,b);
	min = Math.min(min,c);
	return min;
    }
    public static int max(int a, int b,int c) {
	int max= Math.max(a,b);
	max = Math.max(max,c);
        return max;
    }
}
class FastScanner {
    private final InputStream in = System.in;
    private final byte[] buffer = new byte[1024];
    private int ptr = 0;
    private int buflen = 0;
    private boolean hasNextByte() {
        if (ptr < buflen) {
            return true;
        } else {
            ptr = 0;
            try {
                buflen = in.read(buffer);
            } catch (IOException e) {
                e.printStackTrace();
            }
            if (buflen <= 0) {
                return false;
            }
        }
        return true;
    }

    private int readByte() {
        if (hasNextByte())
            return buffer[ptr++];
        else
            return -1;
    }

    private boolean isPrintableChar(int c) {
        return 33 <= c && c <= 126;
    }

    public boolean hasNext() {
        while (hasNextByte() && !isPrintableChar(buffer[ptr]))
            ptr++;
        return hasNextByte();
    }

    public String next() {
        if (!hasNext())
            throw new NoSuchElementException();
        StringBuilder sb = new StringBuilder();
        int b = readByte();
        while (isPrintableChar(b)) {
            sb.appendCodePoint(b);
            b = readByte();
        }
        return sb.toString();
    }

    public long nextLong() {
        if (!hasNext())
            throw new NoSuchElementException();
        long n = 0;
        boolean minus = false;
        int b = readByte();
        if (b == '-') {
            minus = true;
            b = readByte();
        }
        if (b < '0' || '9' < b) {
            throw new NumberFormatException();
        }
        while (true) {
            if ('0' <= b && b <= '9') {
                n *= 10;
                n += b - '0';
            } else if (b == -1 || !isPrintableChar(b)) {
                return minus ? -n : n;
            } else {
                throw new NumberFormatException();
            }
            b = readByte();
        }
    }

    public int nextInt() {
        long nl = nextLong();
        if (nl < Integer.MIN_VALUE || nl > Integer.MAX_VALUE)
            throw new NumberFormatException();
        return (int) nl;
    }

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


import java.util.Arrays;
import java.util.Scanner;

public class Main {
	public static void main(String[] args) {
		Scanner input = new Scanner(System.in);
		int n = input.nextInt();
		int k = input.nextInt();
		int[] h = new int[n];
		int s = 0;
		for (int i = 0; i < n; i++) {
			h[i] = input.nextInt();
		}
		if (k >= n) {
			System.out.println(0);
		}else {
			Arrays.sort(h);
			for(int i = 0; i < n-k ;i++) {
				s += h[i];
			}
			System.out.printf("%d",s);
		}

	}
}


import java.util.*; import java.io.*; import java.math.*;
public class Main{
	//Don't have to see. start------------------------------------------
	static class InputIterator{
		ArrayList<String> inputLine = new ArrayList<String>(1024);
		int index = 0; int max; String read;
		InputIterator(){
			BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
			try{
				while((read = br.readLine()) != null){
					inputLine.add(read);
				}
			}catch(IOException e){}
			max = inputLine.size();
		}
		boolean hasNext(){return (index < max);}
		String next(){
			if(hasNext()){
				return inputLine.get(index++);
			}else{
				throw new IndexOutOfBoundsException("There is no more input");
			}
		}
	}
	static HashMap<Integer, String> CONVSTR = new HashMap<Integer, String>();
	static InputIterator ii = new InputIterator();//This class cannot be used in reactive problem.
	static PrintWriter out = new PrintWriter(System.out);
	static void flush(){out.flush();}
	static void myout(Object t){out.println(t);}
	static void myerr(Object t){System.err.print("debug:");System.err.println(t);}
	static String next(){return ii.next();}
	static boolean hasNext(){return ii.hasNext();}
	static int nextInt(){return Integer.parseInt(next());}
	static long nextLong(){return Long.parseLong(next());}
	static double nextDouble(){return Double.parseDouble(next());}
	static ArrayList<String> nextStrArray(){return myconv(next(), 8);}
	static ArrayList<String> nextCharArray(){return myconv(next(), 0);}
	static ArrayList<Integer> nextIntArray(){
		ArrayList<String> input = nextStrArray(); ArrayList<Integer> ret = new ArrayList<Integer>(input.size());
		for(int i = 0; i < input.size(); i++){
			ret.add(Integer.parseInt(input.get(i)));
		}
		return ret;
	}
	static ArrayList<Long> nextLongArray(){
		ArrayList<String> input = nextStrArray(); ArrayList<Long> ret = new ArrayList<Long>(input.size());
		for(int i = 0; i < input.size(); i++){
			ret.add(Long.parseLong(input.get(i)));
		}
		return ret;
	}
	static String myconv(Object list, int no){//only join
		String joinString = CONVSTR.get(no);
		if(list instanceof String[]){
			return String.join(joinString, (String[])list);
		}else if(list instanceof ArrayList){
			return String.join(joinString, (ArrayList)list);
		}else{
			throw new ClassCastException("Don't join");
		}
	}
	static ArrayList<String> myconv(String str, int no){//only split
		String splitString = CONVSTR.get(no);
		return new ArrayList<String>(Arrays.asList(str.split(splitString)));
	}
	public static void main(String[] args){
		CONVSTR.put(8, " "); CONVSTR.put(9, "\n"); CONVSTR.put(0, "");
		solve();flush();
	}
	//Don't have to see. end------------------------------------------
	static void solve(){//Here is the main function
		ArrayList<Integer> one = nextIntArray();
		int N = one.get(0);
		int K = one.get(1);
		long output = 0;
		ArrayList<Integer> list = nextIntArray();
		Collections.sort(list, Comparator.reverseOrder());
		for(int i = K; i < H; i++){
			output += list.get(i);
		}
		myout(output);
	}
	//Method addition frame start

	//Method addition frame end
}