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:
# -*- 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+=2
    H=[0]+list(map(int,input().split()))+[0]
    edge=[[] for _ in range(N*(K+1))]
    for i in range(N):
        for j in range(K+1):
            for k in range(K+1-j):
                if i+k+1<N:
                    edge[i*(K+1)+j].append((max(H[i+k+1]-H[i],0),(i+k+1)*(K+1)+j+k))
    from heapq import heappop,heappush
    def dijkstra(start,n,edges):
        d=[INF]*n
        used=[False]*n
        d[start]=0
        used[start]=True
        edgelist=[]
        for edge in edges[start]:
            heappush(edgelist,edge)
        while edgelist:
            minedge=heappop(edgelist)
            if used[minedge[1]]:
                continue
            v=minedge[1]
            d[v]=minedge[0]
            used[v]=True
            for edge in edges[v]:
                if not used[edge[1]]:
                    heappush(edgelist,(edge[0]+d[v],edge[1]))
        return d
    d=dijkstra(0,N*(K+1),edge)
    print(min(d[(N-1)*(K+1):]))

if __name__ == '__main__':
    main()

Submission status: Time Limit Exceeded

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

Submission status: Time Limit Exceeded

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(2)]
dp[0][0][0] = 0

for i in range(N):
    for j in range(K+1):
        for k in range(N+1):
            dp[(i+1)%2][j][k] = 10**18
            
    for j in range(K+1):
        for k in range(N+1):
            if j+1<=K:
                dp[(i+1)%2][j+1][k] = min(dp[(i+1)%2][j+1][k], dp[i%2][j][k])
            
            dp[(i+1)%2][j][i+1] = min(dp[(i+1)%2][j][i+1], dp[i%2][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%2][i][j])
    
print(ans)

Submission status: Time Limit Exceeded

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.copy() 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: Time Limit Exceeded

Solution code:
# pylint: disable=invalid-name
# pylint: disable=missing-docstring


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]
                # print('i {} j {} k {} j - (i - k - 1) {} DP_targ {} DP {}'.
                #       format(i, j, k, j - (i - k - 1),
                #              previous + max(H[i] - H[k], 0), DP[i][j]))
    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()

Submission status: Time Limit Exceeded

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

Submission status: Time Limit Exceeded

Solution code:
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=10**9)
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))

Submission status: Time Limit Exceeded

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

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

Submission status: Time Limit Exceeded

Solution code:
n,K=map(int,input().split())
l=list(map(int,input().split()))
INF=float('inf')
dp=[[[] for j in range(K+1)] for i in range(n+1)]
dp[0][0]=[(0,0)]
for i,j in enumerate(l,1):
    a1,b1=dp[i-1][0][0]
    dp[i][0]=[(a1+max(0,j-b1),j)]
for i,j in enumerate(l,1):
    for k in range(1,min(K+1,i+1)):
        tl=dp[i-1][k-1]
        for a1,b1 in dp[i-1][k]:
            tl.append((a1+max(0,j-b1),j))
        tl.sort(reverse=True)
        tl.append((-1,-1))
        x=0
        l1=[]
        while len(tl)-1>x:
            a1,b1=tl[x]
            l1.append(tl[x])
            x+=1
            while tl[x][0]==a1:
                x+=1
        dp[i][k]=l1
a=dp[-1][-1]
a.sort()
print(a[0][0])

Submission status: Time Limit Exceeded

Solution code:
n,K=map(int,input().split())
l=list(map(int,input().split()))
INF=float('inf')
dp=[[[] for j in range(K+1)] for i in range(n+1)]
dp[0][0]=[(0,0)]
for i,j in enumerate(l,1):
    a1,b1=dp[i-1][0][0]
    dp[i][0]=[(a1+max(0,j-b1),j)]
for i,j in enumerate(l,1):
    for k in range(1,min(K+1,i+1)):
        tl=[]
        for a1,b1 in dp[i-1][k]:
            tl.append((a1+max(0,j-b1),j))
        dp[i][k]=tl+dp[i-1][k-1]
a=dp[-1][-1]
a.sort()
print(a[0][0])

Submission status: Time Limit Exceeded

Solution code:
n,K=map(int,input().split())
l=list(map(int,input().split()))
INF=float('inf')
dp=[[[] for j in range(K+1)] for i in range(n+1)]
dp[0][0]=[[0,0]]
for i,j in enumerate(l,1):
    a1,b1=dp[i-1][0][0]
    a1+=max(0,j-b1)
    dp[i][0]=[[a1,j]]
for i,j in enumerate(l,1):
    for k in range(1,min(K+1,i+1)):
        tl=[]
        for a1,b1 in dp[i-1][k]:
            a1+=max(0,j-b1)
            tl.append([a1,j])
        dp[i][k]=tl+dp[i-1][k-1]
print(sorted(dp[-1][-1])[0][0])

Submission status: Time Limit Exceeded

Solution code:
n,k = map(int, input().split( ))
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] = min(mn,h[i])

for i in range(n):##右端
    for j in range(i+1):#本数
        for t in range(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, dp[i][n-k-1])
print(ans)

Submission status: Time Limit Exceeded

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

Submission status: Time Limit Exceeded

Solution code:
# -*- coding: utf-8 -*-

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[i][j] := 列をi個使って、最後に使ったのがj列目の時の最小コスト
dp = list2d(M+1, N+1, INF)
dp[0][0] = 0
for i in range(M):
    for j, h1 in enumerate(A[i:], i):
        if dp[i][j] == INF:
            break
        for k in range(j+1, N+1):
            h2 = A[k]
            dp[i+1][k] = min(dp[i+1][k], dp[i][j] + max(h2 - h1, 0))
print(min(dp[M]))

Submission status: Time Limit Exceeded

Solution code:
# -*- coding: utf-8 -*-

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[i][j] := 列をi個使って、最後に使ったのがj列目の時の最小コスト
dp = list2d(M+1, N+1, INF)
dp[0][0] = 0
for i in range(M):
    for j, h1 in enumerate(A):
        # 枝刈り
        if dp[i][j] == INF:
            continue
        for k in range(j+1, N+1):
            h2 = A[k]
            dp[i+1][k] = min(dp[i+1][k], dp[i][j] + max(h2 - h1, 0))
print(min(dp[M]))

Submission status: Time Limit Exceeded

Solution code:
# -*- coding: utf-8 -*-

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[i][j] := 列をi個使って、最後に使ったのがj列目の時の最小コスト
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]))

Submission status: Time Limit Exceeded

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)
    dp[0, 0] = 0

    for i in range(n):
        h = H[i]
        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.concatenate([(h-s)[:dh], np.zeros(l-dh, dtype=np.int64)])
        for j in range(k+1):
            dp2[j, dh] = min(dp2[j, dh], min(dp[j, :]+temp))
        dp = dp2
    print(np.min(dp))


main()

Submission status: Time Limit Exceeded

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)
    a = max(s)-s
    dp = np.full((1, l), 10**13, dtype=np.int64)
    dp[0, 0] = 0

    if k > 0:
        for i in range(n):
            h = H[i]
            dh = d[h]
            dp2 = np.zeros((min(i+2, k+1), l), dtype=np.int64)
            if i < k:
                s_plus_a = a+dp[:]
                min_s = dp[:]
            else:
                s_plus_a = a+dp[:-1]
                min_s = dp[:-1]
            for j in range(l-2, -1, -1):
                min_s[:, j] = np.minimum(min_s[:, j+1], min_s[:, j])
            for j in range(1, l):
                s_plus_a[:, j] = np.minimum(s_plus_a[:, j-1], s_plus_a[:, j])
            dp2[1:, :] = np.minimum(min_s, s_plus_a - a)
            dp2[0, :] = 10**13
            if i < k:
                for j in range(l):
                    dp2[:-1, dh] = np.minimum(dp2[:-1, dh],
                                              dp[:, j]+max(h-s[j], 0))
            else:
                for j in range(l):
                    dp2[:, dh] = np.minimum(
                        dp2[:, dh], dp[:, j]+max(h-s[j], 0))
            dp = dp2
    else:
        for h in H:
            dh = d[h]
            dp2 = np.full((1, l), 10**13, dtype=np.int64)
            for j in range(l):
                dp2[:, dh] = np.minimum(dp2[:, dh], dp[:, j]+max(h-s[j], 0))
            dp = dp2
    print(np.min(dp))


main()

Submission status: Time Limit Exceeded

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 = [[10**13]*l for _ in range(K+1)]
        t = [[i+j for i, j in zip(a, kk)] for kk in dp]
        min_s = [[dp[i][j] for j in range(l)] for i in range(K+1)]
        for i in range(K+1):
            for j in range(l-2, -1, -1):
                min_s[i][j] = min(min_s[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):
            dp2[i][dh] = min(dp2[i][dh], min(
                [dp[i][j]+max(h-s[j], 0) for j in range(l)]))
        dp = dp2
    print(min([min(i) for i in dp]))


main()

Submission status: Time Limit Exceeded

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)
    a = max(s)-s
    dp = np.full((k+1, l), 10**13, dtype=np.int64)
    dp[0, 0] = 0

    if k > 0:
        for h in H:
            dh = d[h]
            dp2 = np.zeros((k+1, l), dtype=np.int64)
            s_plus_a = a+dp[:-1]
            min_s = dp[:-1]
            for j in range(l-2, -1, -1):
                min_s[:, j] = np.minimum(min_s[:, j+1], min_s[:, j])
            for j in range(1, l):
                s_plus_a[:, j] = np.minimum(s_plus_a[:, j-1], s_plus_a[:, j])
            dp2[1:, :] = np.minimum(min_s, s_plus_a - a)
            dp2[0, :] = 10**13
            for j in range(l):
                dp2[:, dh] = np.minimum(dp2[:, dh], dp[:, j]+max(h-s[j], 0))
            dp = dp2
    else:
        for h in H:
            dh = d[h]
            dp2 = np.full((1, l), 10**13, dtype=np.int64)
            for j in range(l):
                dp2[:, dh] = np.minimum(dp2[:, dh], dp[:, j]+max(h-s[j], 0))
            dp = dp2
    print(np.min(dp))


main()

Submission status: Time Limit Exceeded

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)
    a = max(s)-s
    dp = np.full((k+1, l), 10**13, dtype=np.int64)
    dp[0, 0] = 0
    for h in H:
        dh = d[h]
        dp2 = np.full((k+1, l), 10**13, dtype=np.int64)
        if k > 0:
            t = np.zeros((k, l), dtype=np.int64)
            s_plus_a = a+dp
            min_s = np.array([[j for j in i] for i in dp[:-1]], dtype=np.int64)
            for j in range(l-2, -1, -1):
                min_s[:, j] = np.minimum(min_s[:, j+1], min_s[:, j])
            for j in range(1, l):
                s_plus_a[:, j] = np.minimum(s_plus_a[:, j-1], s_plus_a[:, j])
            t = s_plus_a[:-1] - a
            dp2[1:, :] = np.minimum(min_s, t)
        for j in range(l):
            dp2[:, dh] = np.minimum(dp2[:, dh], dp[:, j]+max(h-s[j], 0))
        dp = dp2
    print(np.min(dp))


main()

Submission status: Time Limit Exceeded

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 = [[10**13]*l for _ in range(K+1)]
        t = [[0]*l for _ in range(K+1)]
        s_plus_a = [[i+j for i, j in zip(a, kk)] for kk in dp]
        min_s = [[dp[i][j] for j in range(l)] for i in range(K+1)]
        for i in range(K+1):
            for j in range(l-2, -1, -1):
                min_s[i][j] = min(min_s[i][j+1], min_s[i][j])
            for j in range(1, l):
                s_plus_a[i][j] = min(s_plus_a[i][j-1], s_plus_a[i][j])
            for j in range(l):
                t[i][j] = s_plus_a[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):
            for j in range(l):
                dp2[i][dh] = min(dp2[i][dh], dp[i][j]+max(h-s[j], 0))
        dp = dp2
    print(min([min(i) for i in dp]))


main()

Submission status: Time Limit Exceeded

Solution code:
import numpy as np
INF = 10**15
def solve(n, k, h):
    dp = np.full((n+1, n+1), INF, dtype=int)
    dp[0, 0] = 0
    h = np.array([0] + h, dtype=int)
    for x in range(1, n+1):
        for y in range(n+1):
            t = np.maximum(h[x] - h[:x], 0)
            dp[x, y] = np.min(dp[:x, y-1] + t)
    return np.min(dp[:, n-k])

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

Submission status: Time Limit Exceeded

Solution code:
import numpy as np
INF = 10**15
def solve(n, k, h):
    dp = np.full((n+1, n+1), INF, dtype=int)
    dp[0, 0] = 0
    h = [0] + h
    for x in range(n+1):
        for y in range(n+1):
            for i in range(x):
                dp[x, y] = min(dp[x, y], dp[i, y-1] + max(0, h[x] - h[i]))
    return np.min(dp[:, n-k])

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

Submission status: Time Limit Exceeded

Solution code:
n, m = list(map(int, input().split()))
if n == m:
  print(0)
  exit()
h = list(map(int, input().split()))
maxi = sum(h)
f = [e for e in h]
# print(f)
for i in range(n - m - 1):
  for j in range(n - 1, i, -1):
    res = maxi
    for k in range(i, j):
      res = min(res, f[k] + max(0, h[j] - h[k]))
    f[j] = res
  # print(f)
print(min(f[n - m - 1:]))

Submission status: Time Limit Exceeded

Solution code:
# F - Laminate
INF = 1001002003004005006
import numpy as np

N, K = map(int, input().split())
M = N - K
H = np.array(list(map(int, input().split())))
H = np.insert(H, 0, 0)

DP = np.full_like(np.zeros([N + 1, M + 1]), INF)
DP[0][0] = 0
for i in range(1, N + 1):
    for j in range(M):
        now = INF
        for k in range(i):
            now = min(now, DP[k][j] + max(0, H[i] - H[k]))
        DP[i][j + 1] = now
        
ans = INF
for i in range(N + 1):
    ans = min(ans, DP[i][M])
    
print(int(ans))

Submission status: Time Limit Exceeded

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


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

print(min([dp[n - k][l] for l in range(n + 1)]))

Submission status: Time Limit Exceeded

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

    DP = [[float("inf")]*(K+1) for i in range(K+1)]
    DP[0][0] = 0
    for i in range(n):
        hi = h[i]
        nxt = [[float("inf")]*(K+1) for i in range(K+1)]
        for j in range(min(i+1, K+1)):
            for k in range(j+1):
                l = i-k-1
                if l<0:
                    left = 0
                else:
                    left = h[l]
                a = hi-left if left<hi else 0
                nxt[j][0] = min(nxt[j][0], DP[j][k]+a)
                if j == K:
                    continue
                nxt[j+1][k+1] = min(nxt[j+1][k+1], DP[j][k])
        DP = nxt

    ans = float("inf")
    for i in DP:
        ans = min(ans, min(i))
    print(ans)

main()

Submission status: Time Limit Exceeded

Solution code:
from array import array

def main():
    n,K = map(int, input().split())
    h = list(map(int, input().split()))
    inf = 1<<60
    DP = [array("q", [inf]*(K+1)) for i in range(K+1)]
    DP[0][0] = 0
    for i in range(n):
        hi = h[i]
        nxt = [array("q", [inf]*(K+1)) for i in range(K+1)]
        for j in range(min(i+1, K+1)):
            for k in range(j+1):
                l = i-k-1
                if l<0:
                    left = 0
                else:
                    left = h[l]
                a = hi-left if left<hi else 0
                nxt[j][0] = min(nxt[j][0], DP[j][k]+a)
                if j == K:
                    continue
                nxt[j+1][k+1] = min(nxt[j+1][k+1], DP[j][k])
        DP = nxt

    ans = float("inf")
    for i in DP:
        ans = min(ans, min(i))
    print(ans)

main()

Submission status: Time Limit Exceeded

Solution code:
from collections import defaultdict

n, k = map(int, input().split())
hhh = list(map(int, input().split()))
INF = 10 ** 18
dp = defaultdict(lambda: INF)
dp[0] = 0
mask1 = (1 << 10) - 1

for h in hhh:
    ndp = defaultdict(lambda: INF)
    h_key = h << 10
    for changed_prev_h, operate in dp.items():
        changed = changed_prev_h & mask1
        prev_h = changed_prev_h >> 10
        if h == prev_h:
            key = h_key + changed
            ndp[key] = min(ndp[key], operate)
        elif h > prev_h:
            key = h_key + changed
            ndp[key] = min(ndp[key], operate + h - prev_h)
            if changed < k:
                key = changed_prev_h + 1
                ndp[key] = min(ndp[key], operate)
        else:
            key = h_key + changed
            ndp[key] = min(ndp[key], operate)
            if changed < k:
                key = changed_prev_h + 1
                ndp[key] = min(ndp[key], operate)
    dp = ndp
print(min(dp.values()))

Submission status: Time Limit Exceeded

Solution code:
from collections import defaultdict
 
n, k = map(int, input().split())
hhh = list(map(int, input().split()))
INF = 10 ** 18
dp = defaultdict(lambda: INF)
dp[0, 0] = 0
for h in hhh:
    ndp = defaultdict(lambda: INF)
    for (changed, prev_h), operate in dp.items():
        if h == prev_h:
            ndp[changed, h] = min(ndp[changed, h], operate)
        elif h > prev_h:
            ndp[changed, h] = min(ndp[changed, h], operate + h - prev_h)
            if changed < k:
                ndp[changed + 1, prev_h] = min(ndp[changed + 1, prev_h], operate)
        else:
            ndp[changed, h] = min(ndp[changed, h], operate)
            if changed < k:
                ndp[changed + 1, prev_h] = min(ndp[changed + 1, prev_h], operate)
    dp = ndp
print(min(dp.values()))

Submission status: Time Limit Exceeded

Solution code:
#!/usr/bin/env python3
from collections import defaultdict,deque
from heapq import heappush, heappop
from bisect import bisect_left, bisect_right
import sys, random, itertools, math
sys.setrecursionlimit(10**5)
input = sys.stdin.readline
sqrt = math.sqrt
def LI(): return list(map(int, input().split()))
def LF(): return list(map(float, input().split()))
def LI_(): return list(map(lambda x: int(x)-1, input().split()))
def II(): return int(input())
def IF(): return float(input())
def LS(): return list(map(list, input().split()))
def S(): return list(input().rstrip())
def IR(n): return [II() for _ in range(n)]
def LIR(n): return [LI() for _ in range(n)]
def FR(n): return [IF() for _ in range(n)]
def LFR(n): return [LI() for _ in range(n)]
def LIR_(n): return [LI_() for _ in range(n)]
def SR(n): return [S() for _ in range(n)]
def LSR(n): return [LS() for _ in range(n)]
mod = 1000000007
inf = float('INF')
from copy import deepcopy

#solve
def solve():
    n, k = LI()
    h = LI()
    d = defaultdict(int)
    d[(0, 0)] = 0
    for i in range(n):
        nd = defaultdict(lambda: inf)
        for key, value in d.items():
            a, b = key
            nd[(h[i], b)] = min(nd[(h[i], b)], value + (h[i] - a if h[i] > a else 0))
            if b + 1 > k:
                continue
            nd[(a, b + 1)] = min(nd[(a, b + 1)], value)
            
        d = nd
    ans = inf
    for i in range(n):
        for j in range(k + 1):
            ans = min(ans, d[(h[i], j)])
    print(ans)
    return


#main
if __name__ == '__main__':
    solve()

Submission status: Time Limit Exceeded

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

N,K = map(int,input().split())
*H, = map(int,input().split())

def f(v):
    L = len(v)
    if L==0:return 0
    ret = min(v)
    v2 = [e-ret for e in v]
    i = 0
    for j in range(L):
        if v2[j]==0:
            ret += f(v2[i:j])
            i = j+1
    else:
        ret += f(v2[i:])
    return ret

def g(v):
    u = []
    w = v[::-1]
    for i,h in enumerate(H):
        if w and i == w[-1]:
            w.pop()
            continue
        u.append(h)
    return f(u)

ans = g([])

dp = [[[ans,[]] for _ in [0]*(K+1)] for _ in [0]*(N+1)]
for i in range(1,N+1):
    for k in range(1,K+1):
        tmp = dp[i-1][k-1][1] + [i-1]
        c = g(tmp)
        if c<dp[i-1][k][0]:
            dp[i][k][0] = c
            dp[i][k][1] = tmp
        else:
            dp[i][k][0] = dp[i-1][k][0]
            dp[i][k][1] = dp[i-1][k][1][:]

print(dp[-1][-1][0])

Submission status: Time Limit Exceeded

Solution code:

import sys
sys.setrecursionlimit(10**6)
readline = sys.stdin.readline 




n,k = [int(i) for i in readline().split()]
a = [0]+[int(i) for i in readline().split()] + [0]

n += 2

INF  = 10**18

diff = [0]
for i in range(n-1):
    diff.append(max(a[i+1]-a[i],0))

from itertools import accumulate
acc = list(accumulate(diff))

ans = {}

def calc(p,q,k):
    if (p,q,k) in ans: return ans[(p,q,k)]
    if k == 0:
        res = acc[q] - acc[p]
    elif k == q-p-1:
        res = max(0,a[q] - a[p])
    else:
        res = INF
        for i in range(p+1,q):
            for l in range(min(k+1,i-p)):
                if k-l > q-p-1: break
                #if p ==1 and q == 4 and k == 1: print(i,l)
                res = min(res, calc(p,i,l)+calc(i,q,k-l))
    #print(p,q,k,res)    
    ans[(p,q,k)] = res    
    return res

#print(acc)
#print(a,n)
print(calc(0,n-1,k))
#print(calc(0,n-1,k))

Submission status: Time Limit Exceeded

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

for _ in range(k):
    h.remove(max(h))
cnt = 0
while sum(h) > 0:
    flag = False
    for idx in range(len(h)):
        if h[idx]>0:
            if not flag:
                flag = True
                cnt += 1
            h[idx] -= 1
        else:
            flag = False
print(cnt)

Submission status: Time Limit Exceeded

Solution code:
from collections import defaultdict

n, k = map(int, input().split())
hhh = list(map(int, input().split()))
INF = 10 ** 18
dp = defaultdict(lambda: INF)
dp[0, 0] = 0
for h in hhh:
    ndp = defaultdict(lambda: INF)
    for (changed, prev_h), operate in dp.items():
        if h == prev_h:
            ndp[changed, h] = min(ndp[changed, h], operate)
        elif h > prev_h:
            ndp[changed, h] = min(ndp[changed, h], operate + h - prev_h)
            if changed < k:
                ndp[changed + 1, prev_h] = min(ndp[changed + 1, prev_h], operate)
        else:
            ndp[changed, h] = min(ndp[changed, h], operate)
            if changed < k:
                ndp[changed + 1, prev_h] = min(ndp[changed + 1, prev_h], operate)
    dp = ndp
print(min(dp.values()))