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



Sample input:
4 1
2 3 4 1


Sample output:
3

Submission status: Time Limit Exceeded

Solution code:
import math,string,itertools,fractions,heapq,collections,re,array,bisect,sys,copy,functools
import time,random

sys.setrecursionlimit(10**7)
inf = 10**20
eps = 1.0 / 10**10
mod = 10**9+7
dd = [(-1,0),(0,1),(1,0),(0,-1)]
ddn = [(-1,0),(-1,1),(0,1),(1,1),(1,0),(1,-1),(0,-1),(-1,-1)]

def LI(): return list(map(int, sys.stdin.readline().split()))
def LLI(): return [list(map(int, l.split())) for l in sys.stdin.readlines()]
def LI_(): return [int(x)-1 for x in sys.stdin.readline().split()]
def LF(): return [float(x) for x in sys.stdin.readline().split()]
def LS(): return sys.stdin.readline().split()
def I(): return int(sys.stdin.readline())
def F(): return float(sys.stdin.readline())
def S(): return input()
def pf(s): return print(s, flush=True)
def pe(s): return print(str(s), file=sys.stderr)
def JA(a, sep): return sep.join(map(str, a))
def JAA(a, s, t): return s.join(t.join(map(str, b)) for b in a)


def main():
    n,k = LI()
    a = LI()
    c = collections.defaultdict(lambda: inf)
    c[(0,0)] = 0
    for t in a:
        nc = collections.defaultdict(lambda: inf)
        for ck,cv in c.items():
            k1,k2 = ck
            if k1 >= t:
                if nc[(t,k2)] > cv:
                    nc[(t,k2)] = cv
            else:
                if nc[(t,k2)] > cv + t-k1:
                    nc[(t,k2)] = cv + t-k1
            if k2 < k:
                if nc[(k1,k2+1)] > cv:
                    nc[(k1,k2+1)] = cv
        c = nc

    return min(c.values())


print(main())

Submission status: Accepted

Solution code:
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)

Submission status: Accepted

Solution code:
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)

Submission status: Accepted

Solution code:
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()

Submission status: Accepted

Solution code:
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))

Submission status: Accepted

Solution code:
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)]  # (直前のインデックス, 使ったk) =>　最小
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)

Submission status: Accepted

Solution code:

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


def solve(K,H):
    # dp[i][k] = H[i]は消さずH[:i]まででk列消したと仮定した時の(H[:i+1]の)コスト
    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))

Submission status: Accepted

Solution code:
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])

Submission status: Accepted

Solution code:
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))

Submission status: Accepted

Solution code:
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):
#     dp[i][0] = float("inf")
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)

Submission status: Accepted

Solution code:
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[i][j]はi番目まで見て，j個の要素からなる
    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()

Submission status: Accepted

Solution code:
def main():
    INF = 10**12
    N, K = list(map(int, input().split()))
    H = list(map(int, input().split()))
    H = [0] + H
    # dp[n][k][l]: n列目までで合計k列Hの値を変えている＆直近l列を変えている場合の塗りの回数の最小値
    # 答えは min_{k,l}(dp[N][k][l])
    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()

Submission status: Accepted

Solution code:
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])
    #for v in dp:
    #    print(v)
    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
"""

Submission status: Accepted

Solution code:
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]))

Submission status: Accepted

Solution code:
n,k = map(int, input().split( ))
if n==k:
    print(0)
    exit()
h = list(map(int, input().split( )))
#h = [0]+h#h[0]=0追加
inf = 10**15

dp = [[inf]*n for _ in range(n+1)] #dp[i][j]右端がi、j+1本残す
mn = h[0]
for i in range(n):
    #mn = min(mn,h[i])
    dp[i][0] = h[i]#min(mn,h[i])

for i in range(1,n):##右端
    for j in range(i+1):#本数
        for t in range(j-1,i):#右から2番目,
            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)

Submission status: Accepted

Solution code:
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]))

Submission status: Accepted

Solution code:
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]))

Submission status: Accepted

Solution code:
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)

Submission status: Accepted

Solution code:
# -*- coding: utf-8 -*-
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()

Submission status: Accepted

Solution code:
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)

Submission status: Accepted

Solution code:
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()

Submission status: Accepted

Solution code:
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)

Submission status: Accepted

Solution code:
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]))

Submission status: Accepted

Solution code:
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)

Submission status: Accepted

Solution code:
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])

Submission status: Accepted

Solution code:
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])

Submission status: Accepted

Solution code:
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])

Submission status: Accepted

Solution code:
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)))

Submission status: Accepted

Solution code:
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):
        #dp[i][k] = min(dp[i][k],dp[i-1][l] + abs)
        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)

Submission status: Accepted

Solution code:
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])
#print(dp)
res = inf
for j in range(K + 1): res = min(res, min(dp[-1][j]))
print(res)

Submission status: Accepted

Solution code:
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)

Submission status: Accepted

Solution code:
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]))

Submission status: Accepted

Solution code:
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()

Submission status: Accepted

Solution code:
def main():
    N, K = (int(i) for i in input().split())
    H = [0] + [int(i) for i in input().split()]
    # 1-indexed
    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()

Submission status: Accepted

Solution code:
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)

Submission status: Accepted

Solution code:
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):
        # print(dp[i])
        ans = min(ans, dp[i][N-K])
    print(ans)


if __name__ == '__main__':
    main()

Submission status: Accepted

Solution code:
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):
        # print(dp[i])
        ans = min(ans, dp[i][N-K])
    print(ans)


if __name__ == '__main__':
    main()

Submission status: Accepted

Solution code:
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):
        # print(dp[i])
        ans = min(ans, dp[i][N-K])
    print(ans)


if __name__ == '__main__':
    main()

Submission status: Accepted

Solution code:
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()

Submission status: Accepted

Solution code:
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()

Submission status: Accepted

Solution code:
N,K=map(int,input().split())
H=list(map(int,input().split()))+[0]
h=[0]*(N+1)
h[0]=H[0]
for i in range(1,N):
    h[i]=max(H[i]-H[i-1],h[i])
for i in range(1,N+1):
    h[i]+=h[i-1]
data=[[0]*N for i in range(N)]
for L in range(N):
    for R in range(L,N):
        if L==0:
            data[L][R]=h[-1]-h[R+1]+H[R+1]
        else:
            data[L][R]=h[L-1]+h[-1]-h[R+1]+max(0,H[R+1]-H[L-1])
for L in range(N):
    for R in range(L,N):
        data[L][R]=h[-1]-data[L][R]
dp=[[0]*(K+1) for i in range(N+1)]
for i in range(1,N+1):
    for j in range(min(i+1,K+1)):
        dp[i][j]=dp[i-1][j]
        for k in range(j-1,-1,-1):
            if dp[i][j]<dp[i-1-j+k][k]+data[i-j+k][i-1]:
                dp[i][j]=dp[i-1-j+k][k]+data[i-j+k][i-1]
print(h[-1]-max(dp[N]))

Submission status: Accepted

Solution code:
N, K = map(int, input().split())
H = list(map(int, [0] + input().split() + [0]))
d = [[10**18]*(K+1) for _ in range(N+2)]
for i in range(K+1):
    d[0][i] = 0
for hi in range(N+1):
    hi+=1
    h = H[hi]
    for i in range(min(K+1, hi)):
        for k in range(i+1):
            d[hi][i] = min(d[hi][i], d[hi-k-1][i-k] + max(H[hi-k-1]-h, 0))
print(min(d[-1]))

Submission status: Accepted

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

import sys
import math
from bisect import bisect_right as br
from bisect import bisect_left as bl
sys.setrecursionlimit(2147483647)
from heapq import heappush, heappop,heappushpop
from collections import defaultdict
from itertools import accumulate
from collections import Counter
from collections import deque
from operator import itemgetter
from itertools import permutations
mod = 10**9 + 7
inf = float('inf')
def I(): return int(sys.stdin.readline())
def LI(): return list(map(int,sys.stdin.readline().split()))

"""
[解説AC]
塗っていくときにかかるコストはΣmax(0,h[i]-h[i-1])
k回まで高さを変えられる⇒k列は考えなくてよい(k列をその左と同じ高さにする)
残るのはn-k列のブロック
ある一列を残すと決めたとき、それにかかるコストはそれより前で残すと決めた列の高さに依存するため
dp[i][j] := i列目を残すとしたとき、i列目まででj列残す場合のコストの最小値とする
dp[i][j] = min(dp[i][j],dp[l][j-1] + max(0,h[i] - h[l])) (1<=l<i) (前回l列目を残し、今回i列目を残す場合)
ans = min(dp[i][n-k])
"""

n,k = LI()
h = [0] + LI()
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):
        for l in range(i):
            dp[i][j] = min(dp[i][j],dp[l][j-1] + max(0,h[i]-h[l]))

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