Problem:


Score : 300 points

Problem Statement

In a flower bed, there are N flowers, numbered 1,2,......,N. Initially, the heights of all flowers are 0.
You are given a sequence h=\{h_1,h_2,h_3,......\} as input. You would like to change the height of Flower k to h_k for all k (1 \leq  k \leq N), by repeating the following "watering" operation:

Specify integers l and r. Increase the height of Flower x by 1 for all x such that l \leq x \leq r.

Find the minimum number of watering operations required to satisfy the condition.

Constraints

1 \leq N  \leq 100

0 \leq h_i \leq 100

All values in input are integers.

Input

Input is given from Standard Input in the following format:

N
h_1 h_2 h_3 ...... h_N

Output

Print the minimum number of watering operations required to satisfy the condition.

Sample Input 1

4
1 2 2 1

Sample Output 1

2

The minimum number of watering operations required is 2.
One way to achieve it is:

Perform the operation with (l,r)=(1,3).

Perform the operation with (l,r)=(2,4).

Sample Input 2

5
3 1 2 3 1

Sample Output 2

5

Sample Input 3

8
4 23 75 0 23 96 50 100

Sample Output 3

221



Sample input:
4
1 2 2 1


Sample output:
2

Submission status: Accepted

Solution code:
N = int(input())
h = list(map(int, input().split()))
count = min(h)
h2 = [x - count for x in h]
searched = 0
while max(h2) > 0:
    if h2[0] == 0:
        found = False
        for i in range(searched+1,N):
            if h2[i] > 0 and found == False:
                found = True
                left = i
            elif found == False and h2[i] == 0:
                searched = i
            elif found == True and h2[i] == 0:
                right = i
                temp = min(h2[left:right])
                for i in range(left,right):
                    h2[i] -= temp
                count += temp
                break
        else:
            temp = min(h2[left:])
            for i in range(left,N):
                h2[i] -= temp
            count += temp
    else:
        left = 0
        for i in range(1,N):
            if h2[i] == 0:
                right = i
                temp = min(h2[left:right])
                for i in range(left,right):
                    h2[i] -= temp
                count += temp
                break
print(count)

Submission status: Accepted

Solution code:
"""
N <= 100
h <= 100
ということで,実装さえすれば通りそう
山の絵を書いて考える
"""

N = int(input())
H = [-1] + list(map(int, input().split()))

ans = 0
for _ in range(max(H)):
    count = 0
    for j in range(N):
        if H[j] <= 0 and H[j+1] > 0:
            count += 1
    ans += count
    H = [i-1 for i in H]
        
print(ans)

Submission status: Accepted

Solution code:
import sys

sys.setrecursionlimit(10 ** 6)
INF = float("inf")
MOD = 10 ** 9 + 7


def input():
    return sys.stdin.readline().strip()


def check(H):
    N = len(H)
    for i in range(N):
        if H[i] != 0:
            return False

    return True


def main():
    N = int(input())
    H = list(map(int, input().split()))

    ans = 0
    while True:
        if check(H):
            break

        # 区間分割
        i = 0
        while i < N:
            if H[i] == 0:
                i += 1
            else:
                # 区間が始まる
                ans += 1
                while i < N and H[i] > 0:
                    H[i] -= 1
                    i += 1

    print(ans)


if __name__ == "__main__":
    main()

Submission status: Accepted

Solution code:
n = int(input())
h_list = [int(h) for h in input().split()]

def count_watering(h_list):
    count = 0
    temp = min(h_list)
    if temp > 0:
        count += temp
        h_list = [h - temp for h in h_list]
    
    l = r = 0
    for i in range(len(h_list)):
        if h_list[i] > 0:
            r = i + 1
            continue
        
        if l != r:
            count += count_watering(h_list[l:r])
        l = r = i + 1
    else:
        if l != r:
            count += count_watering(h_list[l:r])
    
    return count

print(count_watering(h_list))

Submission status: Accepted

Solution code:
n = int(input())
h_input = list(map(int,input().split()))

ans=0

for i in range(max(h_input)):
    x = h_input[:]
    for j in range(n):
        if j==0 and x[0]!=0:#左端
            ans+=1
            h_input[j]-=1
        if j!=0:
            if x[j-1]==0 and x[j]!=0:#探索の左が0でかつ自身が0になっていない解き
                ans+=1
            if x[j]!=0:
                h_input[j]-=1
print(ans)

Submission status: Accepted

Solution code:
n=int(input())
h=list(map(int,input().split()))
p=0
for i in range(1,101):
    a=False
    for j in h:
        if i<=j and not(a):
            p+=1
            a=True
        if a and i>j:
            a=False
        #print(i,j,a)
print(p)

Submission status: Accepted

Solution code:
def main():
    N = int(input())
    H = [int(_) for _ in input().split()]
    H.append(0)

    count = 0
    while True:
        continueCount = 0
        breakFrag = True
        for i in range(0, N+1):
            v = H[i]
            if v >= 1:
                count = count + 1
                H[i] = v - 1
                continueCount = continueCount + 1
                breakFrag = False
            else:
                if continueCount > 1:
                    count = count - (continueCount - 1)
                continueCount = 0
        if breakFrag:
            break
    print(count)





if __name__ == "__main__":
    main()

Submission status: Accepted

Solution code:
n=int(input())
h=list(map(int,input().split()))
ans=0
for i in range(max(h)):
    x=h[:]
    for j in range(n):
        if j==0 and x[0]!=0:
            ans+=1
            h[j]-=1
        if j!=0:
            if x[j-1]==0 and x[j]!=0:
                ans+=1
            if x[j]!=0:
                h[j]-=1
print(ans)

Submission status: Accepted

Solution code:
from collections import defaultdict, deque, Counter
from heapq import heappush, heappop, heapify
from itertools import permutations, accumulate, combinations, combinations_with_replacement
from math import sqrt, ceil, floor, factorial
from bisect import bisect_left, bisect_right, insort_left, insort_right
from copy import deepcopy
from operator import itemgetter
from functools import reduce
from fractions import gcd
import sys
def input(): return sys.stdin.readline().rstrip()
def I(): return int(input())
def Is(): return map(int, input().split())
def LI(): return list(map(int, input().split()))
def TI(): return tuple(map(int, input().split()))
def IR(n): return [I() for _ in range(n)]
def LIR(n): return [LI() for _ in range(n)]
def TIR(n): return [TI() for _ in range(n)]
def S(): return input()
def Ss(): return input().split()
def LS(): return list(input())
def SR(n): return [S() for _ in range(n)]
def SsR(n): return [Ss() for _ in range(n)]
def LSR(n): return [LS() for _ in range(n)]
sys.setrecursionlimit(10**6)
MOD = 10**9+7
INF = 10**18
# ----------------------------------------------------------- #

n = I()
H = LI()
def dfs(A):
    if not A:
        return 0
    m = min(A)
    mi = A.index(m)
    B = [x-m for x in A[:mi]]
    C = [x-m for x in A[mi+1:]]
    return m + dfs(B) + dfs(C)
print(dfs(H))

Submission status: Accepted

Solution code:
n = int(input())
h_list = list(map(int, input().split()))

max_h = max(h_list)

cnt_water = 0
for i in range(1, max_h+1)[::-1]:
    watering = False
    for j in range(n):
        if h_list[j] == i:
            if not watering:
                cnt_water += 1
                watering = True
            h_list[j] -= 1
        else:
            watering = False
print(cnt_water)

Submission status: Accepted

Solution code:
#print#!/usr/bin/env python3
#%% for atcoder uniittest use
import sys
input= lambda: sys.stdin.readline().rstrip()
sys.setrecursionlimit(10**9)
def pin(type=int):return map(type,input().split())
def tupin(t=int):return tuple(pin(t))
def lispin(t=int):return list(pin(t))
#%%code
from fractions import gcd
import math
def resolve():
    N=pin()
    X=tupin()
    ans=0
    for h in range(101):
        if (X)==[0]*(len(X)):
            print(ans)
            return

        cnt=0
        f=0
        for j in range(len(X)):
            if X[j]>0:f=1
            if f and X[j]==0:
                f=0
                cnt+=1
        if X[-1]!=0:cnt+=1
        ans+=(cnt)
        #print(X,cnt)

        temp=[]
        for x in X:
            if x>0:
                temp.append(x-1)
            else:temp.append(x)
        X=temp
        #print("".join(X).split("0"))
#%%submit!      
resolve()

Submission status: Accepted

Solution code:
import sys
sys.setrecursionlimit(10 ** 6)
# input = sys.stdin.readline    ####
int1 = lambda x: int(x) - 1
def II(): return int(input())

def MI(): return map(int, input().split())
def MI1(): return map(int1, input().split())

def LI(): return list(map(int, input().split()))
def LI1(): return list(map(int1, input().split()))
def LLI(rows_number): return [LI() for _ in range(rows_number)]

def printlist(lst, k='\n'): print(k.join(list(map(str, lst))))
INF = float('inf')

from collections import deque
def solve():
    n = II()
    H = LI()

    d = deque()

    def split_0(lst):
        res = []
        tmp = []
        for l in lst:
            if l == 0:
                if len(tmp) > 0:
                    res.append(tmp)
                    tmp = []
            else:
                tmp.append(l)
        if len(tmp) > 0:
            res.append(tmp)
        return res

    r = split_0(H)
    d.extend(r)
    # print(d)

    cnt = 0
    while len(d) > 0:
        lst = d.popleft()
        mn = min(lst)
        res = split_0(list(map(lambda x: x - mn, lst)))
        cnt += mn
        d.extend(res)
    print(cnt)




if __name__ == '__main__':
    solve()

Submission status: Accepted

Solution code:
import sys
sys.setrecursionlimit(10 ** 6)
# input = sys.stdin.readline    ####
int1 = lambda x: int(x) - 1
def II(): return int(input())

def MI(): return map(int, input().split())
def MI1(): return map(int1, input().split())

def LI(): return list(map(int, input().split()))
def LI1(): return list(map(int1, input().split()))
def LLI(rows_number): return [LI() for _ in range(rows_number)]

def printlist(lst, k='\n'): print(k.join(list(map(str, lst))))
INF = float('inf')

def dfs(lst, cnt):

    sub = []
    min_ = INF
    # print(lst, cnt, sub, min_)
    for l in lst:
        if l == 0:
            if min_ != INF:
                # print(min_, sub)
                cnt += min_
                cnt = dfs(list(map(lambda x: x-min_, sub)) + [0], cnt)
                sub = []
                min_ = INF
            else:
                continue
        else:
            min_ = min(min_, l)
            sub.append(l)
    # print('a')
    return cnt

def solve():
    n = II()
    H = LI()

    ans = dfs(H + [0], cnt=0)
    print(ans)

if __name__ == '__main__':
    solve()

Submission status: Accepted

Solution code:
N = int(input())
H = list(map(int, input().split()))
 
n = H[0]
 
for i in range(1, N):
    if H[i] > H[i-1]:
        n += H[i] - H[i-1]
 
print(n)

Submission status: Accepted

Solution code:
N = int(input())
H = list(map(int, input().split()))

n = H[0]

for i in range(1, N):
    if H[i] > H[i-1]:
        n += H[i] - H[i-1]

print(n)

Submission status: Accepted

Solution code:
N = int(input())
H = list(map(int, input().split()))

n = H[0]
k = H[0]

for i in range(1, N):
    if H[i] > k:
        n += H[i] - k
    k = H[i]
print(n)

Submission status: Accepted

Solution code:
import sys
import numpy as np


def count_water(np_arr):
  if not np_arr.any():
    return 0
  least = min(np_arr)
  div_p = np.where(np_arr == least)[0][0]
  np_arr -= least
  return least + count_water(np_arr[:div_p]) + count_water(np_arr[div_p + 1:])


def main():
  readline = sys.stdin.readline
  
  n = int(readline().rstrip())
  h = np.array(tuple(int(_) for _ in readline().rstrip().split()))
  
  print(count_water(h))

 
if __name__ == "__main__":
  main()

Submission status: Accepted

Solution code:
#!/usr/bin/env python3

import sys
# import math
# from string import ascii_lowercase, ascii_upper_case, ascii_letters, digits, hexdigits
# import re                                    # re.compile(pattern) => ptn obj; p.search(s), p.match(s), p.finditer(s) => match obj; p.sub(after, s)
# from operator import itemgetter              # itemgetter(1), itemgetter('key')
# from collections import deque                # deque class. deque(L): dq.append(x), dq.appendleft(x), dq.pop(), dq.popleft(), dq.rotate()
# from collections import defaultdict          # subclass of dict. defaultdict(facroty)
# from collections import Counter              # subclass of dict. Counter(iter): c.elements(), c.most_common(n), c.subtract(iter)
# from heapq import heapify, heappush, heappop # built-in list. heapify(L) changes list in-place to min-heap in O(n), heappush(heapL, x) and heappop(heapL) in O(lgn).
# from heapq import nlargest, nsmallest        # nlargest(n, iter[, key]) returns k-largest-list in O(n+klgn).
# from itertools import count, cycle, repeat   # count(start[,step]), cycle(iter), repeat(elm[,n])
# from itertools import groupby                # [(k, list(g)) for k, g in groupby('000112')] returns [('0',['0','0','0']), ('1',['1','1']), ('2',['2'])]
# from itertools import starmap                # starmap(pow, [[2,5], [3,2]]) returns [32, 9]
# from itertools import product, permutations  # product(iter, repeat=n), permutations(iter[,r])
# from itertools import combinations, combinations_with_replacement
# from itertools import accumulate             # accumulate(iter[, f])
# from functools import reduce                 # reduce(f, iter[, init])
# from functools import lru_cache              # @lrucache ...arguments of functions should be able to be keys of dict (e.g. list is not allowed)
# from bisect import bisect_left, bisect_right # bisect_left(a, x, lo=0, hi=len(a)) returns i such that all(val<x for val in a[lo:i]) and all(val>-=x for val in a[i:hi]).
# from copy import deepcopy                    # to copy multi-dimentional matrix without reference
# from fractions import gcd                    # for Python 3.4 (previous contest @AtCoder)


def main():
    mod = 1000000007                # 10^9+7
    inf = float('inf')              # sys.float_info.max = 1.79...e+308
    # inf = 2 ** 64 - 1               # (for fast JIT compile in PyPy) 1.84...e+19
    sys.setrecursionlimit(10**6)    # 1000 -> 1000000
    def input(): return sys.stdin.readline().rstrip()
    def ii():    return int(input())
    def mi():    return map(int, input().split())
    def mi_0():  return map(lambda x: int(x)-1, input().split())
    def lmi():   return list(map(int, input().split()))
    def lmi_0(): return list(map(lambda x: int(x)-1, input().split()))
    def li():    return list(input())


    def watering(seq, prev, i):
        if prev == i:
            return 0
        min_val = min(seq[prev:i])
        for ind in range(prev, i):
            seq[ind] -= min_val
        return min_val
    
    
    n = ii()
    L = lmi()
    cnt = 0
    while any(map(lambda x: x>0, L)):
        # print(L)
        prev = 0
        for i in range(n):
            if L[i] == 0:
                cnt += watering(L, prev, i)
                prev = i + 1
            elif i == n - 1:
                cnt += watering(L, prev, n)
    print(cnt)


if __name__ == "__main__":
    main()

Submission status: Accepted

Solution code:
n = int(input())
h = [int(i) for i in input().split()]
ans = 0
for i in range(n-1):
    flag = True
    while flag:
        flag = False
        t = n - i
        for j in range(i+1):
            if 0 not in h[j:j+t]:
                for k in range(t):
                    h[j+k] -= 1
                flag = True
                ans += 1
print(ans + sum(h))

Submission status: Accepted

Solution code:
import sys
input = sys.stdin.readline

#n = int(input())
#l = list(map(int, input().split()))

'''
A=[]
B=[]
for i in range():
    a,b = map(int, input().split())
    x=
    A.append(a)
    B.append(b)'''

n=int(input())
h=list(map(int,input().split()))
cnt=0
while sum(h)>0:
    pv=0
    pone=0
    for i in range(n):
        if h[i]!=0 and pv==0:# 最初に1確定
            pone+=1
        pv=h[i]
    cnt+=pone
    h=[i-1 if i>0 else 0 for i in h]
    #print(h,cnt)
print(cnt)

Submission status: Accepted

Solution code:
n=int(input())
h=list(map(int,input().split()))
hm=max(h)
s=['']*hm
for k in range(1,hm+1):
  for i in range(n):
    if h[i]>=k:
      s[k-1]+='#'
    else:
      s[k-1]+=' '

#print(s)
ans=0
for k in range(hm):
  ans+=len(list(s[k].split()))
print(ans)

Submission status: Accepted

Solution code:
n = int(input())
H = list(map(int, input().split()))
ans = 0
while sum(H) > 0:
    prev = 0
    split = 0
    for h in H:
        if prev == 0 and h != 0:
            split += 1
        prev = h
    ans += split
    H = [h-1 if h > 0 else 0 for h in H]

print(ans)

Submission status: Accepted

Solution code:
n = int(input())
H = list(map(int, input().split()))
ans = H[0]
for i in range(1, n):
    ans += max(0, H[i]-H[i-1])
print(ans)

Submission status: Accepted

Solution code:
N = int(input())
flower_plan = [int(i) for i in input().split()]

# だるま落としのようにやる
cnt = 0
while True:
    if not any(flower_plan):
        break
    else :
        i = 0
        while i < N:
            if flower_plan[i] == 0:
                i += 1
            else :
                cnt += 1
                while i < N and flower_plan[i] > 0:
                    flower_plan[i] -= 1
                    i += 1
print(cnt)

Submission status: Accepted

Solution code:
n=int(input())
l=list(map(int,input().split()))
now=0
ans=0
for x in l:
  if x>now:
    ans+=(x-now)
  now=x
print(ans)

Submission status: Accepted

Solution code:
n = int(input())
l = list(map(int,input().split()))
c = 0
if n==1:
  print(*l)
  exit()
while l.count(0)!=n:
  for i in range(n-1):
    if l[i]==0 and i!=n-2:
      continue
    elif l[i]==0 and i==n-2:
      c += 1
      l[n-1] -=1
    elif l[i]<=l[i+1] and i!=n-2:
      l[i] -= 1
    elif l[i]<=l[i+1] and i==n-2:
      l[i] -= 1
      l[i+1] -=1
      c += 1
    else:
      c += 1
      l[i] -= 1
      break
print(c)

Submission status: Accepted

Solution code:
n = int(input())
l = list(map(int,input().split()))
ans = []
i = 0
while l != [0]*n:
  for s in range(n):
    if l[s] != 0:
      start = s
      break
  mini = 101
  flag = True
  i = start
  while flag:
    if l[i] != 0:
      mini = min(mini,l[i])
      if i == n-1:
        for k in range(start,n):
          l[k] -= mini
        ans.append(mini)
        flag = False
        i = -1
    else:
      for j in range(start,i):
        l[j] -= mini
      ans.append(mini)
      flag = False
    i += 1 
print(sum(ans))

Submission status: Accepted

Solution code:
def find_lr(H):
    max_length = 0
    max_right = 0
    seq_cnt = 0
    for i, h in enumerate(H):
        if h > 0:
            seq_cnt += 1
            if i == len(H) - 1:
                if seq_cnt > max_length:
                    max_length = seq_cnt
                    max_right = i
        else:
            if seq_cnt > max_length:
                max_length = seq_cnt
                max_right = i - 1
            seq_cnt = 0
    return (max_right - max_length + 1, max_right)


def main():
    N = int(input())
    H = list(map(int, input().split(' ')))
    cnt = 0
    while sum(H) > 0:
        l, r = find_lr(H)
        for i in range(l, r + 1):
            H[i] -= 1
        cnt += 1
    print(cnt)


if __name__ == '__main__':
    main()

Submission status: Accepted

Solution code:
import collections
import numpy as np
import sys
sys.setrecursionlimit(10**8)
#N,K=map(int,input().split())
N=int(input())
h=np.array(list(map(int,input().split())))
ans=0
def sol(l,m,k):
    global ans
    if m==0:
        return ans
    elif m>0:
        for i in range(N-m+1):
            if not 0 in l[i:i+m]:
                ans+=np.amin(l[i:i+m])
                l[i:i+m]=l[i:i+m]-min(l[i:i+m])
                #print(l)
        sol(l,m-1,ans)
    # else:
    #     ans+=np.count_nonzero(h)
    #     sol(l, m - 1, ans)
n=0
sol(h,N,ans)
print(ans)

Submission status: Accepted

Solution code:
import sys
read = sys.stdin.buffer.read
readline = sys.stdin.buffer.readline
readlines = sys.stdin.buffer.readlines
sys.setrecursionlimit(10 ** 7)

n, *h = map(int, read().split())
ans = h[0]
for bf, af in zip(h, h[1:]):
    if af > bf:
        ans += af - bf
print(ans)

Submission status: Accepted

Solution code:
import sys
read = sys.stdin.buffer.read
readline = sys.stdin.buffer.readline
readlines = sys.stdin.buffer.readlines
sys.setrecursionlimit(10 ** 7)

n, *h = map(int, read().split())
ans = 0
flag = False
for bf, af in zip(h, h[1:]):
    if bf <= af:
        if flag:
            ans += t - bf
        flag = False
    else:
        if not flag:
            t = bf
        flag = True
if flag:
    ans += t
else:
    ans += h[-1]
print(ans)

Submission status: Accepted

Solution code:
import sys
input = sys.stdin.readline
from collections import *
 
n = int(input())
h = list(map(int, input().split()))+[0]
ans = 0

while True:
    for i in range(n):
        if h[i]>0 and h[i+1]==0:
            ans +=1
            
    able=True
    
    for j in range(n):
        if h[j]>0:
            h[j]-=1
            able=False
            
    if able:
        break
        
print(ans)

Submission status: Accepted

Solution code:
from statistics import median
#import collections
#aa = collections.Counter(a) # list to list || .most_common(2)で最大の2個とりだせるお a[0][0]
from fractions import gcd
from itertools import combinations # (string,3) 3回
from collections import deque
from collections import defaultdict
import bisect
#
#    d = m - k[i] - k[j]
#    if kk[bisect.bisect_right(kk,d) - 1] == d:
#
#
#
# pythonで無理なときは、pypyでやると正解するかも！！
#
#

import sys
sys.setrecursionlimit(10000000)
mod = 10**9 + 7

def readInts():
  return list(map(int,input().split()))

def main():
    n = int(input())
    H = readInts()
    cnt = 0
    while True:
        #print(H)
        allzero = True
        i = 0
        while i < n:
            if H[i] != 0:
                l = i
                cnt += 1
                allzero = False
                break
            i += 1
        if allzero:
            print(cnt)
            exit()
        while l < n:
            if H[l] != 0:
                H[l] -=1
            else:
                break
            l += 1
if __name__ == '__main__':
  main()

Submission status: Accepted

Solution code:
import sys
input = sys.stdin.readline

n = int(input())
h = [int(x) for x in input().split()]

ans = 0

def solve(l, r):
    global ans
    if l >= r:
        return
    if 0 not in h[l:r]:
        minh = min(h[l:r])
        ans += minh
        for i in range(l, r):
            h[i] -= minh
        solve(l, r)
    else:
        for i in range(l, r):
            if h[i] == 0:
                solve(l, i)
                l = i + 1
        solve(l, r)
solve(0, n)

print(ans)

Submission status: Accepted

Solution code:
n = int(input())
H = list(map(int, input().split()))
H = [-1]+H+[-1]
ans = 0
for i in range(1, 101):
    for j in range(1, n+1):
        if H[j] >= i and H[j-1] < i:
            ans += 1
print(ans)

Submission status: Accepted

Solution code:
import sys
input = sys.stdin.readline
sys.setrecursionlimit(10**7)
from collections import Counter, deque
from collections import defaultdict
from itertools import combinations, permutations, accumulate, groupby, product
from bisect import bisect_left,bisect_right
from heapq import heapify, heappop, heappush
from math import floor, ceil
from operator import itemgetter
def I(): return int(input())
def MI(): return map(int, input().split())
def LI(): return list(map(int, input().split()))
def LI2(): return [int(input()) for i in range(n)]
def MXI(): return [[LI()]for i in range(n)]
def printns(x): print('\n'.join(x))
def printni(x): print('\n'.join(list(map(str,x))))
inf = 10**17
mod = 10**9 + 7
#s=input().rstrip()

n=I()
lis=LI()
count=0
while sum(lis)>0:
    i=0
    state=""
    while i<n:
        if lis[i]>0:
            lis[i]-=1
            state="water"
            #print(1)
        elif lis[i]==0 and state=="water":
            count+=1
            state=""
            #print(2)
        if i==n-1 and state=="water":
            count+=1
            state=""
            #print(3)
        i+=1
print(count)

Submission status: Accepted

Solution code:
import sys, heapq, bisect, math, fractions
from collections import deque
from collections import Counter
from collections import OrderedDict

N = int(input())
H = list(map(int, sys.stdin.readline().rsplit()))

res = 0
i = 0
ok = False

while ok is False:
    streak = False
    ok = True
    
    for i, h in enumerate(H):
        if h > 0:
            ok = False
            H[i] -= 1
            streak = True
        elif h == 0 and streak is True:
            streak = False
            res += 1
    else:
        if ok is False and streak is True:
            res += 1

print(res)

Submission status: Accepted

Solution code:
N = int(input())
H = [0] + list(map(int, input().split())) + [0]

ans = 0
while any(H):
    water = min(h for h in H if h)

    cnt = 0
    bl = 0
    for x, y in zip(H[:-1], H[1:]):
        if x < y and x == 0:
            bl = 1
        elif x > y and y == 0 and bl:
            cnt += 1
            bl = 0
    ans += water * cnt
    H = [max(0, h-water) for h in H]


print(ans)

Submission status: Accepted

Solution code:
import sys
sys.setrecursionlimit(1000000)
def watering(l,a,b):
  if b==a:
    return 0
  if b-a <= 1:
    return l[a]
  
  c = 0
  t = a
  
  mi = min(l[a:b])
  for i in range(a,b):
    l[i] -= mi
    
  for i in range(a,b):
    if l[i]==0:
      c += watering(l,t,i)
      t=i+1
  c += watering(l,t,b)
      
  return c+mi

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

print(watering(h,0,n))

Submission status: Accepted

Solution code:
import sys
input = sys.stdin.readline

n = int(input())
h = [int(x) for x in input().split()]

ans = 0

while h != [0]*n:
    # print(h)
    left = 0
    for right in range(left, n):
        if h[right] == 0:
            if len(h[left:right]):
                minh = min(h[left:right])
                ans += minh
                for i in range(left, right):
                    h[i] -= minh
            left = right + 1
    if left <= right:
        if len(h[left:right + 1]):
            minh = min(h[left:right + 1])
            ans += minh
            for i in range(left, right + 1):
                h[i] -= minh
print(ans)

Submission status: Accepted

Solution code:
N = int(input())
H = list(map(int,input().split()))
A = []
while sum(H)>0:
    hmin = 101
    cur = 0
    for i in range(N):
        h = H[i]
        if h>0:
            hmin = min(hmin,h)
        elif hmin<=100:
            A.append(hmin)
            for j in range(cur,i):
                H[j] -= hmin
            cur = i+1
            hmin = 101
        else:
            cur = i+1
    if cur<N:
        A.append(hmin)
        for j in range(cur,N):
            H[j] -= hmin
        hmin = 101
print(sum(A))

Submission status: Accepted

Solution code:
n = int(input())
h = list(map(int, input().split()))

ans = 0
while sum(h) != 0:
    sakki = 1
    for i in range(n):
        if h[i] != 0:
            h[i] -= 1
            sakki = 1
        else:
            if sakki == 0:
                continue
            else:
                if i != 0:
                    ans += 1
                    sakki = 0
                else:
                    sakki = 0
    if sakki == 1:
        ans += 1

print(ans)

Submission status: Accepted

Solution code:
from collections import deque
from heapq import heapify,heappop,heappush,heappushpop
from copy import copy,deepcopy
from itertools import product,permutations,combinations,combinations_with_replacement
from collections import defaultdict,Counter
from bisect import bisect_left,bisect_right
# from math import gcd,ceil,floor,factorial
# from fractions import gcd
from functools import reduce
from pprint import pprint

INF = float("inf")

def myinput():
    return map(int,input().split())

def mylistinput(n):
    return [ list(myinput()) for _ in range(n) ]

def mycol(data,col):
    return [ row[col] for row in data ]

def mysort(data,col,reverse_flag):
    data.sort(key=lambda x:x[col],reverse=reverse_flag)
    return data

def mymax(data):
    M = -1*float("inf")
    for i in range(len(data)):
        m = max(data[i])
        M = max(M,m)
    return M

def mymin(data):
    m = float("inf")
    for i in range(len(data)):
        M = min(data[i])
        m = min(m,M)
    return m

def mycount(ls,x):
    # lsはソート済みであること
    l = bisect_left(ls,x)
    r = bisect_right(ls,x)
    return (r-l)

def myoutput(ls,space=True):
    if space:
        if len(ls)==0:
            print(" ")
        elif type(ls[0])==str:
            print(" ".join(ls))
        elif type(ls[0])==int:
            print(" ".join(map(str,ls)))
        else:
            print("Output Error")
    else:
        if len(ls)==0:
            print("")
        elif type(ls[0])==str:
            print("".join(ls))
        elif type(ls[0])==int:
            print("".join(map(str,ls)))
        else:
            print("Output Error")

n = int(input())
h = list(myinput())
h = [0] + h
m = 0
ans = 0
for i in range(n):
    a = h[i]
    b = h[i+1]
    if a<=b:
        if (i+1)==n:
            ans += b - m
        else:
            pass
    else:
        ans += a - m
        m = b
print(ans)

Submission status: Accepted

Solution code:
import numpy as np
N=int(input())

H=list(map(int, input().split()))
H=np.array(H)
MAX=H.max()

ans=0
for i in range(MAX):
    nowzero=True
    count=0
    for j in range(N):
        if nowzero:
            if H[j]>0:
                nowzero=False
                count+=1
        else:
            if H[j]<=0:
                nowzero=True
    ans+=count
    #print(H)
    H-=1

#print(H)
print(ans)

Submission status: Accepted

Solution code:
N = int(input())
flowers = list(map(int, input().split()))
now = 0
ans = 0
for h in flowers:
    if now < h:
        ans += (h - now)
        now = h
    else:
        now = h
print(ans)

Submission status: Accepted

Solution code:
import sys
input = sys.stdin.readline
from collections import *

N = int(input())
h = list(map(int, input().split()))+[0]
ans = 0

while True:
    for i in range(N):
        if h[i]>0 and h[i+1]==0:
            ans += 1
            
    flag = True
    
    for j in range(N):
        if h[j]>0:
            h[j] -= 1
            flag = False
    
    if flag:
        break

print(ans)

Submission status: Accepted

Solution code:
n=int(input())
h=list(map(int,input().split()))+[0]
ans=0
while sum(h):
  for i in range(n):
    if h[i]>0 and h[i+1]==0:ans+=1
    h[i]=max(0,h[i]-1)
print(ans)

Submission status: Accepted

Solution code:
import sys
import os

def file_input():
    f = open('ABC116/input.txt', 'r')
    sys.stdin = f

def minusmin(a):
    # print(a)
    if len(a)==1:
        # print('end:'+str(a[0]))
        return a[0]
    else:
        a_min=min(a)
        # print('min:'+str(a_min))
        # print(a_min)
        j=0
        out=a_min
        for i in range(len(a)):
            a[i]-=a_min
            if a[i]==0:
                # print("j="+str(j)+" i="+str(i))
                if i!=j:
                    out+=minusmin(a[j:i])
                j=i+1
            elif i==len(a)-1 and a[i]!=0:
                out+=minusmin(a[j:i+1])
        return out

def main():
    #file_input()
    N=int(input())
    h_li=list(map(int, input().split()))

    print(minusmin(h_li))


if __name__ == '__main__':
    main()

Submission status: Accepted

Solution code:
N = int(input())
h = list(map(int, input().split()))

c = 0
now = 0
for i in range(N):
    if h[i] > now:
        c += h[i] - now
    now = h[i]

print(c)