Problem:
 Score : 600 points    Problem Statement We will create an artwork by painting black some squares in a white square grid with 10^9 rows and N columns. The current plan is as follows: for the i -th column from the left, we will paint the H_i bottommost squares and will not paint the other squares in that column. Before starting to work, you can choose at most K columns (possibly zero) and change the values of H_i for these columns to any integers of your choice between 0 and 10^9 (inclusive). Different values can be chosen for different columns.  Then, you will create the modified artwork by repeating the following operation:   Choose one or more consecutive squares in one row and paint them black. (Squares already painted black can be painted again, but squares not to be painted according to the modified plan should not be painted.)   Find the minimum number of times you need to perform this operation.      Constraints  1 \leq N \leq 300  0 \leq K \leq N  0 \leq H_i \leq 10^9  All values in input are integers.         Input Input is given from Standard Input in the following format:  N  K  H_1  H_2  ...  H_N       Output Print the minimum number of operations required.        Sample Input 1 4 1
2 3 4 1      Sample Output 1 3  For example, by changing the value of H_3 to 2 , you can create the modified artwork by the following three operations:   Paint black the 1 -st through 4 -th squares from the left in the 1 -st row from the bottom.  Paint black the 1 -st through 3 -rd squares from the left in the 2 -nd row from the bottom.  Paint black the 2 -nd square from the left in the 3 -rd row from the bottom.        Sample Input 2 6 2
8 6 9 1 2 1      Sample Output 2 7       Sample Input 3 10 0
1 1000000000 1 1000000000 1 1000000000 1 1000000000 1 1000000000      Sample Output 3 4999999996

Solution (Python):
n,k=map(int,input().split())
dp=[]
for i in range(n+2):
  dp.append([])
  for j in range(n+2):
    dp[-1].append([])
    for l in range(k+1):
      dp[-1][-1].append(10**12)
for l in range(k+1):
    dp[0][0][l]=0
h=list(map(int,input().split()))
h.append(0)
h.reverse()
h.append(0)
h.reverse()
for i in range(1,n+2):
  for j in range(n+2):
    for l in range(k+1):
      dp[i][i][l]=min(dp[i][i][l],dp[i-1][j][l]+max(0,h[i]-h[j]))
      if l>0:
        dp[i][j][l]=min(dp[i][j][l],dp[i-1][j][l-1])
        dp[i][0][l]=min(dp[i][0][l],dp[i-1][j][l-1]+h[j])
ans=dp[n+1][0][0]
for j in range(n+2):
  for l in range(k+1):
    ans=min(ans,dp[n+1][j][l])
print(ans)

Solution (Python):
N,K = map(int,input().split())

H = list(map(int,input().split()))

HSorted = sorted(H)

HIndexToHeight = []
HHeightToIndex = {}

for i in range(N):
    if i != 0 and HSorted[i] == HSorted[i-1]:
        continue
    HIndexToHeight.append(HSorted[i])
    HHeightToIndex[HSorted[i]] = len(HIndexToHeight) - 1

INF = 10 ** 12

heightCount = len(HIndexToHeight)

DP = []
for i in range(N):
    DP.append([])
    for j in range(K + 1):
        DP[i].append([])
        for k in range(heightCount):
            DP[i][j].append(INF)

for k in range(heightCount):
    if k == HHeightToIndex[H[0]]:
        DP[0][0][k] = H[0]
    elif K != 0:
        DP[0][1][k] = HIndexToHeight[k]

for i in range(1,N):
    currentHeight = HHeightToIndex[H[i]]
    for j in range(K + 1):
        for k in range(heightCount):
            if currentHeight > k:
                if j > 0:
                    DP[i][j][k] = min(DP[i-1][j-1][k], DP[i][j][k])
                DP[i][j][currentHeight] = min(DP[i-1][j][k] + HIndexToHeight[currentHeight] - HIndexToHeight[k], DP[i][j][currentHeight])
            elif currentHeight == k:
                DP[i][j][currentHeight] = min(DP[i-1][j][k], DP[i][j][currentHeight])
            else:
                if j > 0:
                    DP[i][j][k] = min(DP[i-1][j-1][k], DP[i][j][k])
                DP[i][j][currentHeight] = min(DP[i-1][j][k], DP[i][j][currentHeight])
ans = INF

for j in range(K + 1):
    for k in range(heightCount):
        if ans > DP[N-1][j][k]:
            ans = DP[N-1][j][k]
if K == N:
    print(0)
else:
    print(ans)

Solution (Python):
import sys

readline = sys.stdin.readline
MOD = 10 ** 9 + 7
INF = float('INF')
sys.setrecursionlimit(10 ** 5)


def main():
    N, K = map(int, readline().split())
    H = [0] + list(map(int, readline().split())) + [0]

    dp = [[INF] * (N + 1) for _ in range(N + 1)]

    for i in range(N + 1):
        dp[i][0] = 0

    for i in range(1, N + 1):
        dp[i][1] = H[i]
        for j in range(2, i + 1):
            for k in range(1, i):
                dp[i][j] = min(dp[i][j], dp[k][j - 1] + max(0, H[i] - H[k]))

    ans = INF
    for i in range(1, N + 1):
        ans = min(ans, dp[i][N - K])
    print(ans)

if __name__ == '__main__':
    main()

Solution (Python):
INF = float("inf")

N, K, *H = map(int, open(0).read().split())
H = [0] + H

if N == K:
    print(0)
    quit()

dp = [0] + [INF] * N
for i in range(1, N - K + 1):
    dp = [INF] * i + [min(dp[k] + max(0, h - H[k]) for k in range(i - 1, j)) for j, h in enumerate(H[i:], i)]

print(min(dp))

Solution (Python):
import math
import sys

N, K = map(int, input().split())
H = [0] + list(map(int, input().split()))
if K == 0:
    ans = 0
    pre = 0
    for h in H:
        ans += max(0, h - pre)
        pre = h
    print(ans)
    sys.exit()
dp = [[math.inf]*(K+1) for _ in range(N+1)]  
dp[0][0] = 0
for i in range(1, N + 1):
    for j in range(i):
        for k in range(K+1):
            dp[i][k] = min(dp[j][k] + max(0, H[i] - H[j]), dp[i][k])
    for j in range(i):
        for k in range(K-1, -1, -1):
            dp[j][k + 1] = dp[j][k]
        dp[j][0] = math.inf
ans = math.inf
for i in range(N + 1):
    ans = min(ans, min(dp[i]))
print(ans)

Solution (Python):
def main():
    n, k = map(int, input().split())
    tmp = list(map(int, input().split()))
    h = [0]
    for v in tmp:
        h.append(v)
    dp = [[float("inf")]*(n-k+1) for i in range(n+1)]
    dp[0][0] = 0
    for i in range(1, n+1):
        for j in range(1, n-k+1):
            tmp = float("inf")
            for l in range(i):
                p = max(0, h[i] - h[l])
                if tmp > dp[l][j-1] + p:
                    tmp = dp[l][j-1] + p
            dp[i][j] = tmp
    ans = float("inf")
    for i in range(n+1):
        if ans > dp[i][n-k]:
            ans = dp[i][n-k]
    print(ans)

if __name__ == "__main__":
    main()

Solution (Python):
LI = lambda: list(map(int, input().split()))

N, K = LI()
H = LI()

INF = 10 ** 15


def main():
    h = [0] + H
    dp = [[INF] * (N + 1) for _ in range(N + 1)]
    dp[0][0] = 0
    for i in range(1, N + 1):
        for j in range(1, i + 1):
            v = INF
            for k in range(i):
                x = max(0, h[i] - h[k])
                v = min(v, dp[k][j - 1] + x)
            dp[i][j] = v

    ans = min([dp[i][N - K] for i in range(N - K, N + 1)])
    print(ans)


if __name__ == "__main__":
    main()

Solution (Python):

max2 = lambda x,y: x if x > y else y
min2 = lambda x,y: x if x < y else y


def solve(K,H):
    
    H = [0]+H+[0]
    N = len(H)
    dp = [[float('inf')]*(i+1) for i in range(N)]
    dp[0] = [0]


    for r,hr in enumerate(H):
        for l,hl in enumerate(H[:r]):
            for k in range(l+1):
                dp[r][k+(r-l-1)] = min2(dp[r][k+(r-l-1)], dp[l][k]+max2(0,hr-hl))
    return dp[-1][K]

if __name__ == '__main__':
    N,K = map(int,input().split())
    H = list(map(int,input().split()))

    print(solve(K,H))

Solution (Python):
INF = 10 ** 15

N, K = map(int, input().split())
Hs = [0] + list(map(int, input().split())) + [0]


dp = [[INF] * (K+1) for _ in range(N+2)]
dp[0][0] = 0

for n in range(1, N+2):
    for k in range(K+1):
        for l in range(1, min(n, k+1)+1):
            dp[n][k] = min(dp[n][k], dp[n-l][k-l+1] + max(0, Hs[n] - Hs[n-l]))

print(dp[N+1][K])

Solution (Python):
import sys
input = sys.stdin.readline

def max2(x,y):
    return x if x > y else y

def min2(x,y):
    return x if x < y else y

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

dp = [[10**9*N for _ in range(N-K+1)] for _ in range(N+1)]

dp[0][0] = 0
for i, h in enumerate(H[1:], start=1):
    for k in range(1, min2(i+1, N-K+1)):
        dp[i][k] = min(dp[j][k-1] + max2(0, h-H[j]) for j in range(i))
print(min(d[-1] for d in dp))

Solution (Python):
import sys
input = lambda : sys.stdin.readline().rstrip()
sys.setrecursionlimit(max(1000, 10**9))
write = lambda x: sys.stdout.write(x+"\n")


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

dp = [[0]*(n+1) for _ in range(n+1)]


for i in range(1, n+1):
    hh = h[i-1]
    for j in range(1, n+1):
        if j==1:
            dp[i][j] = hh
        elif j<=i:
            if i>=2:
                dp[i][j] = min((dp[ii][j-1] + max(0, hh-(h[ii-1] if ii>=1 else 0))) for ii in range(1,i))
            else:
                dp[i][j] = hh
        else:
            dp[i][j] = float("inf")
ans = min(min(dp[nn][kk] for kk in range(n-k, n+1)) for nn in range(1,n+1))
print(ans)

Solution (Python):
import sys
input = sys.stdin.readline

def I(): return int(input())
def MI(): return map(int, input().split())
def LI(): return list(map(int, input().split()))

def main():
    """
    メモ
    K=0なら，左から見て登った数を数える，grandGarden
    K>=1の時，塗る列は左右どちらかと同じ高さにする．同じ高さで何個か連なっていると面倒かも？
    左右どちらかと同じ高さにするというのは逐次的な話，1,1,1,5,4,5,1でK=3なら答えは1
    K個を無視できると考える．
    dp[x][y][k]で，x〜yまで，k個無視と考えれば遷移も含めて5乗くらいで行けそう
    =>0からスタートだけで良い，dp[x][k]で行けそう？．xのところは使っているものとする．
    =>「K回使える」よりも「使った数がいくつか」を記憶しておくほうが楽そう
    """
    N,K=MI()
    H=[0]+LI()
    N+=1
    inf=10**12
    dp=[[inf]*(N) for _ in range(N)]
    
    dp[0][0]=0
    
    for i in range(1,N):
        for j in range(N):
            temp=inf
            for k in range(i):
                temp=min(temp,dp[k][j-1]+max(0,H[i]-H[k]))
            dp[i][j]=temp
    
    ans=inf
    
    for i in range(N):
        ans=min(ans,dp[i][N-K-1])
    print(ans)

main()

Solution (Python):
def main():
    INF = 10**12
    N, K = list(map(int, input().split()))
    H = list(map(int, input().split()))
    H = [0] + H
    
    
    dp = [[[INF for _ in range(K + 1)] for _ in range(K + 1)] for _ in range(N + 1)]
    dp[0][0][0] = 0
    for n in range(1, N + 1):
        for k in range(min(n, K) + 1):
            v = INF
            for l in range(k + 1):
                if l > 0:
                    dp[n][k][l] = dp[n - 1][k - 1][l - 1]
                v = min(v, dp[n - 1][k][l] + max(0, H[n] - H[n - l - 1]))
            dp[n][k][0] = v
    ans = INF
    for k in range(K + 1):
        for l in range(k + 1):
            ans = min(ans, dp[N][k][l])
    print(ans)


if __name__ == '__main__':
    main()

Solution (Python):
def examA():
    N = DI()/dec(7)
    ans = N
    print(N)
    return

def examB():
    ans = 0
    print(ans)
    return

def examC():
    ans = 0
    print(ans)
    return

def examD():
    ans = 0
    print(ans)
    return

def examE():
    ans = 0
    print(ans)
    return

def examF():
    N, K = LI()
    H = LI()
    H.insert(0,0)
    dp = [[[inf]*(K+1)for _ in range(N+1)] for _ in range(N+1)]
    dp[0][0][0] = 0
    for i in range(N):
        for j in range(i+1):
            for k in range(K+1):
                dp[i+1][i+1][k] = min(dp[i+1][i+1][k],dp[i][j][k]+max(0,H[i+1]-H[j]))
                if k<K:
                    dp[i+1][j][k+1] = min(dp[i+1][j][k+1],dp[i][j][k])

    ans = inf
    for j in range(N+1):
        ans = min(ans,dp[-1][j][-1])
    
    
    print(ans)
    return

from decimal import getcontext,Decimal as dec
import sys,bisect,itertools,heapq,math,random
from copy import deepcopy
from heapq import heappop,heappush,heapify
from collections import Counter,defaultdict,deque
read = sys.stdin.buffer.read
readline = sys.stdin.buffer.readline
readlines = sys.stdin.buffer.readlines
def I(): return int(input())
def LI(): return list(map(int,sys.stdin.readline().split()))
def DI(): return dec(input())
def LDI(): return list(map(dec,sys.stdin.readline().split()))
def LSI(): return list(map(str,sys.stdin.readline().split()))
def LS(): return sys.stdin.readline().split()
def SI(): return sys.stdin.readline().strip()
global mod,mod2,inf,alphabet,_ep
mod = 10**9 + 7
mod2 = 998244353
inf = 10**18
_ep = dec("0.000000000001")
alphabet = [chr(ord('a') + i) for i in range(26)]
alphabet_convert = {chr(ord('a') + i): i for i in range(26)}

getcontext().prec = 28

sys.setrecursionlimit(10**7)

if __name__ == '__main__':
    examF()

"""
8 7
7 3 9 1 5 2 8 3
"""

Solution (Python):
n, k = map(int, input().split())
h = [0] + list(map(int, input().split())) + [0]
inf = 10 ** 13
dp = [[0] * (k + 1)]
for i in range(1, n + 2):
    dp.append([inf] * (k + 1))
    for j in range(i):
        for u in range(i - j - 1, k + 1):
            dp[-1][u] = min(dp[-1][u], dp[j][u - i + j + 1] + max(h[i] - h[j], 0))
print(min(dp[-1]))

Solution (Python):
n,k = map(int, input().split( ))
if n==k:
    print(0)
    exit()
h = list(map(int, input().split( )))

inf = 10**15

dp = [[inf]*n for _ in range(n+1)] 
mn = h[0]
for i in range(n):
    
    dp[i][0] = h[i]

for i in range(1,n):
    for j in range(i+1):
        for t in range(j-1,i):
            dp[i][j] = min(dp[i][j], dp[t][j-1] + max(h[i]-h[t], 0))

ans = inf 

for i in range(n):
    ans = min(ans, min(dp[i][n-k-1:]))
print(ans)

Solution (Python):
import sys
input = sys.stdin.readline

N, K = map(int, input().split())
H = [0] + list(map(int, input().split()))
INF = 10**18
dp = [[INF] * (N+1) for _ in range(N+1)]
dp[0][0] = 0
for i in range(1, N+1):
    for j in range(1, N+1):
        for k in range(i):
            dp[j][i] = min(dp[j][i], dp[j-1][k] + max(0, H[i] - H[k]))
print(min(dp[N-K]))

Solution (Python):
def solve():
    INF = 10**12

    def max2(x, y): return x if x >= y else y
    def min2(x, y): return x if x <= y else y

    N, K = map(int, input().split())
    Hs = [0] + list(map(int, input().split()))

    dp = [[INF]*(N+1) for _ in range(N+1)]
    dp[0][0] = 0
    for i in range(1, N+1):
        H = Hs[i]
        diffs = []
        for iPrev in range(i):
            diff = max2(0, H-Hs[iPrev])
            diffs.append(diff)
        dp[i][0] = 0
        dp[i][1] = H
        for j in range(2, min(i, N-K)+1):
            for iPrev in range(i):
                dp[i][j] = min2(dp[i][j], dp[iPrev][j-1]+diffs[iPrev])

    ans = min(dpi[N-K] for dpi in dp)
    print(ans)


solve()

Solution (Python):
import numpy as np

N,K=map(int,input().split())
H=list(map(int,input().split()))
sortedH=np.hstack((np.zeros(1,dtype=np.int64), np.sort(H)))

dic={}
for i,h in enumerate(sortedH):
    dic[h]=i

inf=10**15
dp=np.full((302,len(sortedH)+1),inf,dtype=np.int64)
dp[0,0]=0

for i,h in enumerate(H):
    for k in range(i+1,-1,-1):
        dp[k+1]=np.minimum(dp[k+1],dp[k])
        idx=dic[h]
        ma=np.min(dp[k][:idx]+h-sortedH[:idx])
        mb=np.min(dp[k][idx:])
        dp[k]=np.full(len(sortedH)+1,inf,dtype=np.int64)
        dp[k][idx]=min(ma,mb)
print(np.min(dp[:K+1]))

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

dp=[[float("inf") for j in range(N+1)] for k in range(N)]

for j in range(N):
    dp[j][1]=h[j]
    dp[j][0]=0

for i in range(1,N):
    for j in range(2,N+1):
        dp[i][j]=min(dp[k][j-1]+(h[i]-h[k])*(h[i]>=h[k]) for k in range(i))

test1=min(dp[i][N-K] for i in range(N))
print(test1)

Solution (Python):

import sys
sys.setrecursionlimit(10**9)
INF=10**18
MOD=10**9+7
input=lambda: sys.stdin.readline().rstrip()
YesNo=lambda b: bool([print('Yes')] if b else print('No'))
YESNO=lambda b: bool([print('YES')] if b else print('NO'))
int1=lambda x:int(x)-1

def main():
    N,K=map(int,input().split())
    N+=1
    H=[0]+list(map(int,input().split()))+[0]
    dp=[[INF]*(K+1) for _ in range(N+1)]
    dp[0][0]=0
    for i in range(N):
        for j in range(K+1):
            for k in range(j,K+1):
                if i-(k-j)>=0:
                    dp[i+1][k]=min(dp[i+1][k],dp[i-(k-j)][j]+max(H[i+1]-H[i-(k-j)],0))
                    pass
    print(dp[-1][-1])

if __name__ == '__main__':
    main()

Solution (Python):
n,K = map(int, input().split())
h = list(map(int, input().split()))
h = [0] + h
INF = 1001001001001
dp = [[INF] *(n+1) for _ in range(n+1)]  
dp[0][0] = 0
for j in range(n):
    for i in range(1,n+1):
        for k in range(i):
            dp[i][j+1] = min(dp[i][j+1],dp[k][j]+max(0,h[i]-h[k]))

ans = INF
for i in range(n+1):
    ans = min(ans,dp[i][n-K])

print(ans)

Solution (Python):
import sys
input = sys.stdin.buffer.readline

def main():
    N,K = map(int,input().split())
    H = list(map(int,input().split()))
    H = [0]+H
    INF = 10**15
    
    dp = [INF]*(N+1)
    dp[0] = 0
    for i in range(N-K):
        use = [INF]*(N+1)
        for j in range(i,N+1):
            for k in range(j+1,N+1):
                use[k] = min(use[k],dp[j]+max(0,H[k]-H[j]))
        dp = use
    
    print(min(dp))

if __name__ == "__main__":
    main()

Solution (Python):
N, K = map(int, input().split())
H = list(map(int, input().split())) + [0]
dp = [[10**12]*(K+2) for _ in range(N+1)]
dp[0][0] = 0
for i in range(N):
  for j in range(min(i+1, K) + 1):
    for k in range(j + 1):
      dp[i+1][j] = min(dp[i+1][j], dp[i-k][j-k] + max(H[i] - H[i-k-1], 0))
ans = min(dp[-1])
for i in range(K+1):
  ans = min(ans, dp[N-i][K-i])
print(ans)

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

INF = 10**12
dp = [[INF] * (N+1) for i in range(N+1)]
dp[0][0] = 0

for x in range(1, N+1):
  dp[x][0] = 0
  dp[x][1] = H[x]
  for y in range(2, x+1):
    for i in range(x):
      dp[x][y] = min(dp[x][y], dp[i][y-1]+max(0, H[x]-H[i]))

ans = INF
for i in range(N+1):
  ans = min(ans, dp[i][N-K])

print(ans)

Solution (Python):
import sys
input = sys.stdin.readline

N, K = map(int, input().split())
H = [0]+list(map(int, input().split()))
dp = [[10**18]*(N+1) for _ in range(N-K+1)]
dp[0][0] = 0

for i in range(N-K):
    for j in range(N+1):
        for k in range(j):
            dp[i+1][j] = min(dp[i+1][j], dp[i][k]+max(0, H[j]-H[k]))

print(min(dp[N-K]))

Solution (Python):
import sys
input = sys.stdin.readline

N, K = map(int, input().split())
H = [0]+list(map(int, input().split()))
dp = [[[10**18]*(N+1) for _ in range(K+1)] for _ in range(N+1)]
dp[0][0][0] = 0

for i in range(N):
    for j in range(K+1):
        for k in range(N+1):
            if j+1<=K:
                dp[i+1][j+1][k] = min(dp[i+1][j+1][k], dp[i][j][k])
            
            dp[i+1][j][i+1] = min(dp[i+1][j][i+1], dp[i][j][k]+max(0, H[i+1]-H[k]))

ans = 10**18

for i in range(K+1):
    for j in range(N+1):
        ans = min(ans, dp[N][i][j])
    
print(ans)

Solution (Python):
n,K = map(int,input().split())
a = [0]+list(map(int,input().split()))+[0]
INF = float("inf")
n += 1
dp = [[[INF for i in range(K+1)] for j in range(n+1)] for k in range(n+1)]
dp[0][0][0] = 0
mx = 0
for i in range(1,n+1):
  x = a[i]
  for j in range(i):
    for k in range(1,min(K,i)+1):
      dp[i][j][k] = dp[i-1][j][k-1]
  for k in range(min(K,i)+1):
    for l in range(1,i+1):
      dp[i][i][k] = min(dp[i][i][k],dp[i-1][i-l][k]+max(0,x-a[i-l]))
print(dp[n][n][K])

Solution (Python):
N,K= map(int,input().split())
H = [0]+list(map(int,input().split()))+[0]
dp = [[0]*(K+2) for i in [0]*(N+2)]
for i in range(1,N+2):
    for j in range(K+1):
        dp[i][j] = min([dp[i-k][j-k+1] + max(0,H[i]-H[i-k]) for k in range(1,min(j+1,i)+1)])
print(dp[N+1][K])

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

def dpinit(ps, val=0):
    res = [val for i in [0]*ps[-1]]
    for i in ps[:-1][::-1]:
        res = [res[:] for k in [0]*i]
    return res

H = [0] + H + [0]
dp = dpinit((N+2,K+2))

for i in range(1,N+2):
    for j in range(K+1):
        l = min(j+1,i)
        cand = [dp[i-k][j-k+1] + max(0, H[i]-H[i-k]) for k in range(1,l+1)]
        dp[i][j] = min(cand)

print(dp[N+1][K])

Solution (Python):




def main():
    N, K = map(int, input().split())
    H = [0] + [int(x) for x in input().split()]
    DP = [[-1 for _ in range(K + 1)] for _ in range(N + 1)]
    DP[0] = [0 for _ in range(K + 1)]
    for i in range(1, N + 1):
        for j in range(K + 1):
            for k in range(max(i - j - 1, 0), i):
                previous = DP[k][j - (i - k - 1)]
                if previous == -1:
                    continue

                if DP[i][j] == -1 or previous + max(H[i] - H[k], 0) < DP[i][j]:
                    DP[i][j] = previous + max(H[i] - H[k], 0)

                if j > 0 and DP[i][j - 1] != -1 and DP[i][j - 1] < DP[i][j]:
                    DP[i][j] = DP[i][j - 1]
                
                
                
    ans = -1
    for i in range(N + 1):
        if K < (N - i):
            continue
        if ans == -1 or DP[i][min(K - (N - i), K)] < ans:
            ans = DP[i][min(K - (N - i), K)]
    print(ans)


if __name__ == '__main__':
    main()

Solution (Python):
n, k = map(int, input().split())
H = [0] + list(map(int, input().split()))

m = n - k
DP = [[float("inf")] * (m + 1) for _ in range(n + 1)]

DP[0][0] = 0
for i in range(1, n + 1):
    for j in range(1, m + 1):
        if i < j:
            continue
        DP[i][j] = min(DP[k][j - 1] + max(0, H[i] - H[k]) for k in range(i))

print(min(DP[i][m] for i in range(n + 1)))

Solution (Python):
from functools import lru_cache

n, k = map(int, input().split())
h = [0] + list(map(int, input().split())) + [0]
INF = 10 ** 18


@lru_cache(maxsize=None)
def solve(i, nokori):
    if i == 0:
       return 0
    res = INF
    for j in range(nokori + 1):
        if i - 1 - j < 0:
            break
        diff = max(h[i] - h[i - 1 - j], 0)
        res = min(solve(i - 1 - j, nokori - j) + diff, res)
    return res


print(solve(n + 1, k))

Solution (Python):
ii = lambda : int(input())
mi = lambda : map(int,input().split())
li = lambda : list(map(int,input().split()))

n,K = mi()
hlis = li()

inf = 10 **13 + 7
dp = [[inf]*n for _ in range(n)]
for i in range(n):
    dp[0][i] = hlis[i]

for i in range(1,n):
    for k in range(i,n):
        
        for l in range(k):
            dp[i][k] = min(dp[i][k],dp[i-1][l] + max(0,hlis[k] - hlis[l]))

tukau = n - K
ans = inf
if K == n:
    print(0)
    exit()
for i in range(tukau-1,n):
    ans = min(ans,dp[tukau-1][i])
print(ans)

Solution (Python):
import sys
input = sys.stdin.readline
N, K = map(int, input().split())
a = [0] + list(map(int, input().split()))
inf = 10 ** 12
dp = [[[inf] * (N + 1) for _ in range(K + 1)] for _ in range(N + 1)]
dp[0][0][0] = 0
for i in range(N):
  for j in range(K + 1):
    for k in range(N + 1):
      if dp[i][j][k] == inf: continue
      x = max(0, a[i + 1] - a[k])
      dp[i + 1][j][i + 1] = min(dp[i + 1][j][i + 1], dp[i][j][k] + x)
      if j < K: dp[i + 1][j + 1][k] = min(dp[i + 1][j][k], dp[i][j][k])

res = inf
for j in range(K + 1): res = min(res, min(dp[-1][j]))
print(res)

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

if(n==k):
    print(0)
    exit()

inf = 10**15 * (n+1)
dp = [[inf] * (n-k+1) for _ in range(n+1)]
dp[0][0] = 0

for i in range(1,n+1):
    for j in range(1, n-k+1):
        if(j==1):
            dp[i][j] = h[i-1]
        else:
            tmp = inf
            for l in range(1,i):
                tmp = min(tmp, dp[l][j-1] + max(0, h[i-1]- h[l-1])  )
            dp[i][j] = tmp

ans = inf
for i in range(n+1):
    ans = min(ans, dp[i][-1])

print(ans)

Solution (Python):
import sys
input = sys.stdin.readline

INF = 10**18

N, K = map(int, input().split())
A = [0] + list(map(int, input().split())) + [0]

dp = [[INF]*(K+1) for _ in range(N+2)]
dp[0][0] = 0
for i in range(1, N+2):
    for k in range(K+1):
        tmp = INF
        for j in range(max(0, i-k-1), i):
            tmp = min(tmp, dp[j][k-(i-j-1)] + max(0, A[i]-A[j]))
        dp[i][k] = tmp

print(min(dp[-1]))

Solution (Python):
def main():
    import sys
    input = sys.stdin.readline

    N, K = map(int, input().split())
    H = list(map(int, input().split()))
    H.append(0)
    H.insert(0, 0)
    N += 2

    inf = 10**12
    dp = [[inf] * (K+1) for _ in range(N)]
    dp[0][0] = 0
    for i in range(N):
        for k in range(K+1):
            for j in range(K-k+1):
                if i + j + 1 < N:
                    dp[i+j+1][k+j] = min(dp[i+j+1][k+j], dp[i][k] + max(0, H[i+j+1] - H[i]))
    print(min(dp[-1]))


if __name__ == '__main__':
    main()

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

INF = float('inf')
dp = [[INF]*(N-K+1) for _ in range(N+1)]
dp[0][0] = 0

for i,h in enumerate(H):
    if i==0: continue
    for j in range(N-K,0,-1):
        for k in range(i):
            c = max(0, h - H[k])
            dp[i][j] = min(dp[i][j], dp[k][j-1] + c)
print(min(row[-1] for row in dp))

Solution (Python):
def main():
    N, K = (int(i) for i in input().split())
    H = [0] + [int(i) for i in input().split()]
    
    if N == K:
        return print(0)
    elif K == 0:
        ans = 0
        for i in range(N):
            ans += max(H[i+1] - H[i], 0)
        return print(ans)
    dp = [[10**12]*(N-K+1) for _ in range(N+1)]

    for x in range(N+1):
        dp[x][1] = H[x]

    for y in range(2, N-K+1):
        for x in range(N+1):
            for i in range(1, x):
                dp[x][y] = min(dp[x][y], dp[i][y-1] + max(0, H[x] - H[i]))

    ans = dp[0][N-K]
    for i in range(1, N+1):
        ans = min(ans, dp[i][N-K])
    print(ans)


if __name__ == '__main__':
    main()

Solution (Python):
def solve():
    INF = float('inf')

    def max2(x, y): return x if x >= y else y

    N, K = map(int, input().split())
    Hs = [0] + list(map(int, input().split()))

    if N == K:
        return 0

    dp = [INF] * (N+1)
    dp[0] = 0
    for j in range(1, N-K+1):
        dp2 = [INF] * (N+1)
        for i, H in enumerate(Hs[j:], j):
            for k in range(j-1, i):
                dp2[i] = min(dp2[i], dp[k] + max2(0, H-Hs[k]))
        dp = dp2

    return min(dp)

ans = solve()
print(ans)

Solution (Python):


import sys

def input(): return sys.stdin.readline().strip()
def list2d(a, b, c): return [[c] * b for i in range(a)]
def list3d(a, b, c, d): return [[[d] * c for j in range(b)] for i in range(a)]
def list4d(a, b, c, d, e): return [[[[e] * d for j in range(c)] for j in range(b)] for i in range(a)]
def ceil(x, y=1): return int(-(-x // y))
def INT(): return int(input())
def MAP(): return map(int, input().split())
def LIST(N=None): return list(MAP()) if N is None else [INT() for i in range(N)]
def Yes(): print('Yes')
def No(): print('No')
def YES(): print('YES')
def NO(): print('NO')
sys.setrecursionlimit(10 ** 9)
INF = 10 ** 18
MOD = 10 ** 9 + 7

N, K = MAP()
M = N - K
A = [0] + LIST()


dp = list2d(M+1, N+1, INF)
dp[0][0] = 0
for i in range(1, M+1):
    for j, h1 in enumerate(A):
        for k in range(max(j-N, 0), j):
            h2 = A[k]
            dp[i][j] = min(dp[i][j], dp[i-1][k] + max(h1 - h2, 0))
print(min(dp[M]))

Solution (Python):
def main():
    import sys
    input = sys.stdin.buffer.readline
    N, K = (int(i) for i in input().split())
    H = [0] + [int(i) for i in input().split()]
    if N == K:
        return print(0)
    elif K == 0:
        ans = 0
        for i in range(N):
            ans += max(H[i+1] - H[i], 0)
        return print(ans)

    dp = [[10**10]*(N-K+1) for i in range(N+1)]
    dp[0][0] = 0
    for i, h in enumerate(H):
        if i == 0:
            continue
        dp[i][1] = h
    for i in range(1, N+1):
        for j in range(1, N-K+1):
            for x in range(1, i):
                dp[i][j] = min(dp[i][j], dp[x][j-1] + max(0, H[i] - H[x]))
    ans = 10**10
    for i in range(N+1):
        
        ans = min(ans, dp[i][N-K])
    print(ans)


if __name__ == '__main__':
    main()

Solution (Python):
def main():
    N, K = (int(i) for i in input().split())
    H = [0] + [int(i) for i in input().split()]
    if N == K:
        return print(0)
    elif K == 0:
        ans = 0
        for i in range(N):
            ans += max(H[i+1] - H[i], 0)
        return print(ans)

    dp = [[10**10]*(N-K+1) for i in range(N+1)]
    dp[0][0] = 0
    for i, h in enumerate(H):
        if i == 0:
            continue
        dp[i][1] = h
    for i in range(1, N+1):
        for j in range(1, N-K+1):
            for x in range(1, i):
                dp[i][j] = min(dp[i][j], dp[x][j-1] + max(0, H[i] - H[x]))
    ans = 10**10
    for i in range(N+1):
        
        ans = min(ans, dp[i][N-K])
    print(ans)


if __name__ == '__main__':
    main()

Solution (Python):
def main():
    N, K = (int(i) for i in input().split())
    H = [0] + [int(i) for i in input().split()]
    if N == K:
        return print(0)
    elif K == 0:
        ans = 0
        for i in range(N):
            ans += max(H[i+1] - H[i], 0)
        return print(ans)

    dp = [[10**10]*(N-K+1) for i in range(N+1)]
    dp[0][0] = 0
    for x in range(1, N+1):
        for y in range(N-K+1):
            for i in range(x):
                dp[x][y] = min(dp[x][y], dp[i][y-1] + max(0, H[x] - H[i]))
    ans = 10**10
    for i in range(N+1):
        
        ans = min(ans, dp[i][N-K])
    print(ans)


if __name__ == '__main__':
    main()

Solution (Python):
def main():
    import numpy as np
    n, k = map(int, input().split())
    H = list(map(int, input().split()))
    s = np.array(sorted(set(H+[0])), dtype=np.int64)
    d = {i: j for j, i in enumerate(s)}
    l = len(s)
    dp = np.full((k+1, l), 10**13, dtype=np.int64)
    dp2 = np.zeros((k+1, l), dtype=np.int64)
    dp[0, 0] = 0

    for h in H:
        dh = d[h]
        dp2 = np.zeros((k+1, l), dtype=np.int64)
        dp2[0] = np.full(l, 10**13, dtype=np.int64)
        dp2[1:, :] = dp[:-1, :]
        temp = np.min(
            dp + np.concatenate([(h-s)[:dh], np.zeros(l-dh, dtype=np.int64)]), axis=1)
        dp2[:, dh] = np.minimum(dp2[:, dh], temp[:])
        dp = dp2
    print(np.min(dp))


main()

Solution (Python):
def main():
    n, K = map(int, input().split())
    H = list(map(int, input().split()))
    s = sorted(set(H+[0]))
    d = {i: j for j, i in enumerate(s)}
    l = len(s)
    m = max(s)
    a = [m-i for i in s]
    dp = [[10**13]*l for _ in range(K+1)]
    dp[0][0] = 0
    for h in H:
        dh = d[h]
        dp2 = [[0]*l for _ in range(K+1)]
        dp2[0] = [10**13]*l
        t = [[0]*l for _ in range(K)]
        for i in range(K):
            for j in range(l):
                t[i][j] = dp[i][j]+a[j]
        min_s = [[10**13]*l for i in range(K+1)]

        for i in range(K):
            for j in range(l-2, -1, -1):
                min_s[i][j] = min(dp[i][j+1], min_s[i][j])
            for j in range(1, l):
                t[i][j] = min(t[i][j-1], t[i][j])
            for j in range(l):
                t[i][j] = t[i][j]-a[j]

        for i in range(K):
            for j in range(l):
                dp2[i+1][j] = min(min_s[i][j], t[i][j])

        for i in range(K+1):
            temp = 10**13
            for j in range(l):
                temp = min(temp, dp[i][j]+max(h-s[j], 0))
            dp2[i][dh] = min(dp2[i][dh], temp)
        dp = dp2
    print(min([min(i) for i in dp]))


main()