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: Wrong Answer

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

if k == n:
  l_h = [0 for _ in l_h]
else:
  for i in range(k):
    del_num = []
    for i in range(n):
      if i == 0:
        del_num.append(max(0, l_h[i]-l_h[i+1], l_h[i]))
      elif i == n-1:
        del_num.append(max(0, l_h[i]-l_h[i-1], l_h[i]))
      else:
        del_num.append(max(0, l_h[i]-l_h[i-1], l_h[i]-l_h[i+1]))
    idx = del_num.index(max(del_num))
    l_h[idx] = l_h[idx] - del_num[idx]

d = []
a = []
x = 0
y = 0
while y < len(l_h)-1:
  if l_h[y] == l_h[y+1]:
    l_h.pop(y)
    y -= 1
  y += 1
for i in range(1,len(l_h) - 1):
  if l_h[i-1] > l_h[i] < l_h[i+1]:
    a.append(l_h[i])
    x = 1
for i in range(1,len(l_h) - 1):
  if l_h[i-1] < l_h[i] > l_h[i+1]:
    d.append(l_h[i])
    x = 1
if len(l_h) >= 2:
  if l_h[0] >= l_h[1]:
    d.append(l_h[0])
  if l_h[-1] >= l_h[-2]:
    d.append(l_h[-1])
  print(sum(d) - sum(a))
else:
  print(l_h[0])

Submission status: Wrong Answer

Solution code:
n,k = map(int,input().split())
lis = list(map(int,input().split()))
lis.insert(0,0)
lis.append(0)
n += 2
num = 0
for nu in lis:
    if nu != 0:
        num += 1
if num <= k:
    print(0)
    exit()

for _ in range(k):
    li = [0 for i in range(n)]
    for i in range(n):
        if i != n-1:
            li[i] = max(li[i],lis[i]-lis[i+1])
        if i != 0:
            li[i] = max(li[i],lis[i]-lis[i-1])
    numm = li.index(max(li))
    if numm == 0:
        lis[0] = lis[1]
    elif numm == n-1:
        lis[n-1] = lis[n-2]
    else:
        lis[numm] = min(lis[numm-1],lis[numm+1])
ans = 0
num = 0
for i in range(n):
    if lis[i] >= num:
        num = lis[i]
    else:
        ans += num-lis[i]
        num = lis[i]
ans += num
print(ans)

Submission status: Wrong Answer

Solution code:
# dp[i][j] := i 列目まで見て、i 列目を使うとして、
#             j 列無視した場合の min

N, K = map(int, input().split())
H = [0] + list(map(int, input().split()))
inf = 10**18
dp = [[inf]*(K+1) for _ in range(N+1)]
dp[0][0] = 0
for i, h in enumerate(H[1:], 1):
    for j in range(K+1):
        for k in range(K+1):  # k 列無視する
            if i-k-1 < 0 or j-k < 0:
                continue
            h_p = H[i-k-1]
            #print(h_p)
            dp[i][j] = min(dp[i][j], dp[i-k-1][j-k] + max(0, h - h_p))
        #exit()

#for d in dp:
#    print(d)
print(min(dp[-1]))

Submission status: Wrong Answer

Solution code:
import sys
import math
from collections import defaultdict

sys.setrecursionlimit(10**7)
def input():
    return sys.stdin.readline()[:-1]

mod = 10**9 + 7

def I(): return int(input())
def II(): return map(int, input().split())
def III(): return list(map(int, input().split()))
def Line(N,num):
    if N<=0:
        return [[]]*num
    elif num==1:
        return [I() for _ in range(N)]
    else:
        read_all = [tuple(II()) for _ in range(N)]
        return map(list, zip(*read_all))

#################

N,K = II()
H = III()

if N==1:
    if K>=1:
        print(0)
        exit()
    else:
        print(H[0])
        exit()

ans = 0
for i in range(N):
    if i==0:
        ans += H[i]
    else:
        if H[i]>H[i-1]:
            ans += H[i]-H[i-1]

def calc(H):
    N = len(H)
    x = [0]*N
    for i in range(N):
        if i!=0 and i!=N-1:
            if H[i]>H[i-1] and H[i]>H[i+1]:
                x[i] = min(H[i]-H[i-1], H[i]-H[i+1])
        if i==0:
            if H[i]>H[i+1]:
                x[i] = H[i]-H[i+1]
        if i==N-1:
            if H[i]>H[i-1]:
                x[i] = H[i]-H[i-1]
    return x

for k in range(K):
    x = calc(H)
    maxi = 0
    maxval = 0
    for i in range(N):
        if x[i]>maxval:
            maxval = x[i]
            maxi = i
    if maxval<=0:
        break
    else:
        if maxi==0:
            H[0] = H[1]
            ans -= x[0]
        elif maxi==N-1:
            H[N-1] = H[N-2]
            ans -= x[N-1]
        else:
            H[maxi] = min(H[maxi-1], H[maxi+1])
            ans -= x[maxi]

print(ans)

Submission status: Wrong Answer

Solution code:
import sys,time,random
ti = time.time()

input = sys.stdin.readline

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

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

dg = 10**3
hh = []
for i in range(n):
    hh.append(h[i]*dg+i)
hh.sort()

hhh = []
for i in range(max(0,n-k*5),n):
    hhh.append(hh[i]%dg)

res = h[0]
for i in range(1,n):
    if h[i] > h[i-1]:
        res += h[i]-h[i-1]

k = min(k,len(hhh))

#print(hhh)
#cnt = 0

while True:
    tank = set(random.sample(hhh,k))
    g = []
    for j in range(n):
        if not j in tank:
            g.append(h[j])
    tmp = g[0]
    for j in range(1,len(g)):
        if g[j] > g[j-1]:
            tmp += g[j]-g[j-1]
    
    res = min(res,tmp)
    #print(res)
    sa = time.time()
    #cnt += 1

    #rint(sa-ti)
    if sa-ti > 1.55:
        print(res)
        #print(cnt)
        exit()

Submission status: Wrong Answer

Solution code:
import sys
import math
from collections import defaultdict

sys.setrecursionlimit(10**7)
def input():
    return sys.stdin.readline()[:-1]

mod = 10**9 + 7

def I(): return int(input())
def II(): return map(int, input().split())
def III(): return list(map(int, input().split()))
def Line(N,num):
    if N<=0:
        return [[]]*num
    elif num==1:
        return [I() for _ in range(N)]
    else:
        read_all = [tuple(II()) for _ in range(N)]
        return map(list, zip(*read_all))

#################

N,K = II()
H = III()

if N==1:
    if K>=1:
        print(0)
        exit()
    else:
        print(H[0])
        exit()

ans = 0
for i in range(N):
    if i==0:
        ans += H[i]
    else:
        if H[i]>H[i-1]:
            ans += H[i]-H[i-1]

def calc(H):
    N = len(H)
    x = [0]*N
    for i in range(N):
        if i!=0 and i!=N-1:
            if H[i]>H[i-1] and H[i]>H[i+1]:
                x[i] = min(H[i]-H[i-1], H[i]-H[i+1])
        if i==0:
            if H[i]>H[i+1]:
                x[i] = H[i]-H[i+1]
        if i==N-1:
            if H[i]>H[i-1]:
                x[i] = H[i]-H[i-1]
    return x

for k in range(K):
    x = calc(H)
    maxi = 0
    maxval = 0
    for i in range(N):
        if x[i]>maxval:
            maxval = x[i]
            maxi = i
    if maxi==0:
        H[0] = H[1]
        ans -= x[0]
    elif maxi==N-1:
        H[N-1] = H[N-2]
        ans -= x[N-1]
    else:
        H[maxi] = min(H[maxi-1], H[maxi+1])
        ans -= x[maxi]

print(ans)

Submission status: Wrong Answer

Solution code:
import sys,time,random
ti = time.time()

input = sys.stdin.readline

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

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

dg = 10**3
hh = []
for i in range(n):
    hh.append(h[i]*dg+i)
hh.sort()

hhh = []
for i in range(max(0,n-k-10),n):
    hhh.append(hh[i]%dg)

res = h[0]
for i in range(1,n):
    if h[i] > h[i-1]:
        res += h[i]-h[i-1]

k = min(k,len(hhh))

#print(hhh)
#cnt = 0

while True:
    tank = set(random.sample(hhh,k))
    g = []
    for j in range(n):
        if not j in tank:
            g.append(h[j])
    tmp = g[0]
    for j in range(1,len(g)):
        if g[j] > g[j-1]:
            tmp += g[j]-g[j-1]
    
    res = min(res,tmp)
    #print(res)
    sa = time.time()
    #cnt += 1

    #rint(sa-ti)
    if sa-ti > 1.7:
        print(res)
        #print(cnt)
        exit()

Submission status: Wrong Answer

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

for i in range(k):
    dif = []
    for j in range(len(h) - 2):
        temp = [h[j + 1] - h[j], h[j + 1] - h[j + 2]]
        if temp[0] * temp[1] <= 0:
            dif.append(0)
        else:
            dif.append(min([abs(temp[0]), abs(temp[1])]))
    del h[dif.index(max(dif)) + 1]
count = 0
for i in range(len(h) - 1):
    if h[i] < h[i + 1]:
        count += (h[i + 1] - h[i])
print(count)

Submission status: Wrong Answer

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
mask2 = ((1 << 64) - 1) ^ mask1
cntup = 1 << 10
k_cmp = k << 10

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

Submission status: Wrong Answer

Solution code:
#
# 　　  ⋀_⋀　 
#　　  (･ω･)  
# .／ Ｕ ∽ Ｕ＼
#  │＊　合　＊│
#  │＊　格　＊│ 
#  │＊　祈　＊│ 
#  │＊　願　＊│ 
#  │＊　　　＊│ 
#      ￣
#
import sys
sys.setrecursionlimit(10**6)
input=sys.stdin.readline
from math import floor,ceil,sqrt,factorial,log #log2ないｙｐ
from heapq import heappop, heappush, heappushpop
from collections import Counter,defaultdict,deque
from itertools import accumulate,permutations,combinations,product,combinations_with_replacement
from bisect import bisect_left,bisect_right
from copy import deepcopy
inf=float('inf')
mod = 10**9+7
def pprint(*A): 
    for a in A:     print(*a,sep='\n')
def INT_(n): return int(n)-1
def MI(): return map(int,input().split())
def MF(): return map(float, input().split())
def MI_(): return map(INT_,input().split())
def LI(): return list(MI())
def LI_(): return [int(x) - 1 for x in input().split()]
def LF(): return list(MF())
def LIN(n:int): return [I() for _ in range(n)]
def LLIN(n: int): return [LI() for _ in range(n)]
def LLIN_(n: int): return [LI_() for _ in range(n)]
def LLI(): return [list(map(int, l.split() )) for l in input()]
def I(): return int(input())
def F(): return float(input())
def ST(): return input().replace('\n', '')
def main():
    N,K = MI()
    H=LI()
    if K == 0:
        ans = H[0]
        for i,h in enumerate(H[1:],start=1):
            ans += max(0, h-H[i-1])
        print(ans)
        return
    # if K == 1:
    #     ans = inf
    #     H_changed = [H[1]] + H[:-1]
    #     for i in range(N):
    #         if i == 0:
    #             res = H_changed[0]
    #         else:
    #             res = H[0]
    #         for j in range(1,N):
    #             if j-1 == i:
    #                 res += max(0, H[i]-H_changed[i-1])
    #             else:
    #                 res += max(0,H[i]-H[i-1])
    #         ans = min(res,ans)
            
        
    dp = [[[inf]*2 for _ in range(K+1)]for _ in range(N)] #dp[i][k][0 or 1]
    H_changed = [H[1]] + H[:-1]
    dp[0][0][0] = H[0]
    dp[0][1][1] = H[1]
    for i in range(1,N):
        for k in range(K+1):
            if k >= 1:
                dp[i][k][1] = min(dp[i-1][k-1][0], dp[i-1][k-1][1])
            dp[i][k][0] = min(dp[i-1][k][0] + max(0,H[i] - H[i-1] ), dp[i-1][k][1] + max(0,H[i] - H_changed[i-1]))
            # print(dp[i-1][k][0] + max(0,H[i]))
            # return
    # print(*dp,sep="\n")
    print(min(dp[-1][-1]))
if __name__ == '__main__':
    main()

Submission status: Wrong Answer

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

del_num = []
for i in range(n):
  if i == 0:
    del_num.append(max(0, l_h[i]-l_h[i+1]))
  elif i == n-1:
    del_num.append(max(0, l_h[i]-l_h[i-1]))
  else:
    del_num.append(max(0, l_h[i]-l_h[i-1], l_h[i]-l_h[i+1]))
for i in range(k):
  idx = del_num.index(max(del_num))
  l_h[idx] = l_h[idx] - del_num[idx]
  del_num[idx] = 0

d = []
a = []
x = 0
y = 0
while y < len(l_h)-1:
  if l_h[y] == l_h[y+1]:
    l_h.pop(y)
    y -= 1
  y += 1
for i in range(1,len(l_h) - 1):
  if l_h[i-1] > l_h[i] < l_h[i+1]:
    a.append(l_h[i])
    x = 1
for i in range(1,len(l_h) - 1):
  if l_h[i-1] < l_h[i] > l_h[i+1]:
    d.append(l_h[i])
    x = 1
if len(l_h) >= 2:
  if l_h[0] >= l_h[1]:
    d.append(l_h[0])
  if l_h[-1] >= l_h[-2]:
    d.append(l_h[-1])
  print(sum(d) - sum(a))
else:
  print(l_h[0])

Submission status: Wrong Answer

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
mask2 = ((1 << 32) - 1) ^ mask1
cntup = 1 << 10
k_cmp = k << 10

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

Submission status: Wrong Answer

Solution code:
import sys,time,random
ti = time.time()

input = sys.stdin.readline

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

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

dg = 10**3
hh = []
for i in range(n):
    hh.append(h[i]*dg+i)
hh.sort()

hhh = []
for i in range(max(0,n-2*k-4),n):
    hhh.append(hh[i]%dg)

res = h[0]
for i in range(1,n):
    if h[i] > h[i-1]:
        res += h[i]-h[i-1]

k = min(k,len(hhh))

#print(hhh)

while True:
    tank = set(random.sample(hhh,k))
    g = []
    for j in range(n):
        if not j in tank:
            g.append(h[j])
    tmp = g[0]
    for j in range(1,len(g)):
        if g[j] > g[j-1]:
            tmp += g[j]-g[j-1]
    
    res = min(res,tmp)
    #print(res)
    sa = time.time()
    #rint(sa-ti)
    if sa-ti > 1.4:
        print(res)
        exit()

Submission status: Wrong Answer

Solution code:
#!usr/bin/env python3
from collections import defaultdict,deque
from heapq import heappush, heappop
import sys
import math
import bisect
import random
def LI(): return [int(x) for x in sys.stdin.readline().split()]
def I(): return int(sys.stdin.readline())
def LS():return [list(x) for x in sys.stdin.readline().split()]
def S():
    res = list(sys.stdin.readline())
    if res[-1] == "\n":
        return res[:-1]
    return res
def IR(n):
    return [I() for i in range(n)]
def LIR(n):
    return [LI() for i in range(n)]
def SR(n):
    return [S() for i in range(n)]
def LSR(n):
    return [LS() for i in range(n)]

sys.setrecursionlimit(1000000)
mod = 1000000007

def solve():
    n,k = LI()
    h = LI()
    h.insert(0,0)
    b = [(-h[i+1],i+1) for i in range(n)]
    f = [0]*(n+1)
    b.sort()
    for i in range(k):
        l,j = b.pop(0)
        f[j] = 1
    ans = 0
    l = 0
    for i in range(1,n+1):
        if not f[i]:
            ans += max(0,h[i]-l)
            l = h[i]
    print(ans)
    return

#Solve
if __name__ == "__main__":
    solve()

Submission status: Wrong Answer

Solution code:
n, k=map(int, input().split())
hlist = list(map(int, input().split()))
cost=[]
dead=[0]*n
if n!=1:
    for i in range(n):
        if i==0:
            if hlist[i]>=hlist[i+1]:
                cost.append(hlist[i]-hlist[i+1])
            else:
                cost.append(0)
        elif i==n-1:
            if hlist[i]>=hlist[i-1]:
                cost.append(hlist[i]-hlist[i-1])
            else:
                cost.append(0)
        else:
            if hlist[i]>=hlist[i-1] and hlist[i]>=hlist[i+1]:
                cost.append(hlist[i]-max(hlist[i-1], hlist[i+1]))
            elif hlist[i]<=hlist[i-1] and hlist[i]<=hlist[i+1]:
                cost.append(min(hlist[i-1], hlist[i+1]) - hlist[i])
            else:
                cost.append(0)
    
    #print(cost)
    rest=k
    while rest>0:
        #bango=cost.index(max(cost))
        dd=[i for i, v in enumerate(cost) if v == max(cost)]
        saidai=0
        for ddd in dd:
            if hlist[ddd]>=saidai:
                saidai=hlist[ddd]
                bango=ddd
        hlist=hlist[:bango]+hlist[bango+1:]
        cost=cost[:bango]+cost[bango+1:]
        if bango==0:
            search=[bango]
        elif bango==len(hlist):
            search=[bango-1]
        else:
            search=[bango-1, bango]
        if len(hlist)>=2:
            for i in search:
                if i==0:
                    if hlist[i]>=hlist[i+1]:
                        cost[i]=hlist[i]-hlist[i+1]
                    else:
                        cost[i]=0
                elif i==len(hlist)-1:
                    if hlist[i]>=hlist[i-1]:
                        cost[i]=hlist[i]-hlist[i-1]
                    else:
                        cost[i]=0
                else:
                    if hlist[i]>=hlist[i-1] and hlist[i]>=hlist[i+1]:
                        cost[i]=hlist[i]-max(hlist[i-1], hlist[i+1])
                    elif hlist[i]<=hlist[i-1] and hlist[i]<=hlist[i+1]:
                        cost[i]=min(hlist[i-1], hlist[i+1]) - hlist[i]
                    else:
                        cost[i]=0
            rest-=1
        else:
            if rest>1:
                hlist=[0]
                break
            else:
                break
        
        #print(cost, hlist)
    
    nul=0
    mae=0
    for i in range(len(hlist)):
        if hlist[i]>=mae:
            nul+=hlist[i]-mae
        mae=hlist[i]
    print(nul)
else:
    if k>=1:
        print(0)
    else:
        print(hlist[0])

Submission status: Wrong Answer

Solution code:
import os
import sys

import numpy as np

if os.getenv("LOCAL"):
    sys.stdin = open("_in.txt", "r")

sys.setrecursionlimit(10 ** 9)
INF = float("inf")
IINF = 10 ** 18
MOD = 10 ** 9 + 7
# MOD = 998244353

N, K = list(map(int, sys.stdin.readline().split()))
H = list(map(int, sys.stdin.readline().split()))

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

H = np.array(H, dtype=float)


# @debug
def count(heights, changes):
    H = heights.copy()
    H = H[~changes]
    ret = 0
    cnt = 1
    height = H.min()
    # 普通に数えてみる
    while height != np.inf:
        H -= height
        ret += cnt * height
        H[H == 0.0] = np.inf
        cnt = np.count_nonzero(np.diff((H != np.inf).astype(int)) == 1)
        cnt += H[0] != np.inf
        height = H.min()
    return int(ret)


# 上から何個変えるか、下から何個変えるかを全探索
ans = INF
orders = H.argsort()
for _ in range(K + 1):
    # 変えるやつ
    changes = np.zeros(N, dtype=bool)
    changes[orders[:K]] = True
    ans = min(ans, count(H, changes))
    orders = np.roll(orders, shift=1)
print(ans)

Submission status: Wrong Answer

Solution code:
#設定
import sys
input = sys.stdin.buffer.readline

#ライブラリインポート
from collections import defaultdict
import copy

#入力受け取り
def getlist():
	return list(map(int, input().split()))


#処理内容
def main():
	N, K = getlist()
	H = getlist()
	m = min(H)
	HH = copy.deepcopy(H)
	for i in range(K):
		ind = HH.index(max(HH))
		HH[ind] = m
	ans = m
	#場合分け
	if K == N:
		print(0)
	elif N == 1:
		print(H[0])
	else:
		if HH[0] > HH[1]:
			ans += HH[0] - HH[1]
		else:
			ans += HH[0] - m
		for i in range(1, N - 1):
			if HH[i] > HH[i - 1] and HH[i] > HH[i + 1]:
				ans += HH[i] - max(HH[i - 1], HH[i + 1])
			elif HH[i] > HH[i - 1]:
				ans += HH[i] - HH[i - 1]
			elif HH[i] > HH[i + 1]:
				ans += HH[i] - HH[i + 1]
			else:
				ans += HH[i] - m
		if HH[-1] > HH[-2]:
			ans += HH[-1] - HH[-2]
		else:
			ans += HH[-1] - m
		print(ans)


if __name__ == '__main__':
	main()

Submission status: Wrong Answer

Solution code:
import os
import sys

import numpy as np

if os.getenv("LOCAL"):
    sys.stdin = open("_in.txt", "r")

sys.setrecursionlimit(10 ** 9)
INF = float("inf")
IINF = 10 ** 18
MOD = 10 ** 9 + 7
# MOD = 998244353

N, K = list(map(int, sys.stdin.readline().split()))
H = list(map(int, sys.stdin.readline().split()))

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

H = np.array(H, dtype=float)


# @debug
def count(heights):
    H = heights.copy()
    ret = 0
    cnt = 1
    height = H.min()
    # 普通に数えてみる
    while height != np.inf:
        H -= height
        ret += cnt * height
        H[H == 0.0] = np.inf
        cnt = np.count_nonzero(np.diff((H != np.inf).astype(int)) == 1)
        cnt += H[0] != np.inf
        height = H.min()
    return int(ret)


# 上から何個変えるか、下から何個変えるかを全探索
ans = INF
orders = H.argsort()
for _ in range(K + 1):
    # 変えるやつ
    changes = np.zeros(N, dtype=bool)
    changes[orders[:K]] = True
    heights = H.copy()
    tmp = np.inf
    for i in range(N):
        if changes[i]:
            heights[i] = tmp
        else:
            tmp = heights[i]
    tmp = np.inf
    for i in reversed(range(N)):
        if changes[i]:
            heights[i] = min(heights[i], tmp)
        else:
            tmp = heights[i]
    ans = min(ans, count(heights))
    orders = np.roll(orders, shift=1)
print(ans)

Submission status: Wrong Answer

Solution code:

from collections import defaultdict,deque
import sys,heapq,bisect,math,itertools,string,queue,copy,time
import numpy as np
sys.setrecursionlimit(10**8)
INF = float('inf')
mod = 10**9+7
eps = 10**-7
def inp(): return int(sys.stdin.readline())
def inpl(): return list(map(int, sys.stdin.readline().split()))
def inpl_str(): return list(sys.stdin.readline().split())

N,K = inpl()
dp = np.zeros((N,K+1),np.uint64)
HH = inpl()


bHs = np.zeros((K+1),int)
for n,H in enumerate(HH):
    for k in reversed(range(1,K+1)):
        used = dp[n-1][k-1]
        unused = dp[n-1][k] + max(0,H-bHs[k])
        # print(bHs,used,unused)
        if used < unused:
            dp[n][k] = used
            bHs[k] = bHs[k-1]
        else:
            dp[n][k] = unused
            bHs[k] = H

    dp[n][0] = dp[n-1][0] + max(0,H-bHs[0])
    bHs[0] = H

    # print(dp[n], bHs)

print(min(dp[-1]))

Submission status: Wrong Answer

Solution code:
n, k=map(int, input().split())
hlist = list(map(int, input().split()))
cost=[]
dead=[0]*n
if n!=1:
    for i in range(n):
        if i==0:
            if hlist[i]>=hlist[i+1]:
                cost.append(hlist[i]-hlist[i+1])
            else:
                cost.append(0)
        elif i==n-1:
            if hlist[i]>=hlist[i-1]:
                cost.append(hlist[i]-hlist[i-1])
            else:
                cost.append(0)
        else:
            if hlist[i]>=hlist[i-1] and hlist[i]>=hlist[i+1]:
                cost.append(hlist[i]-max(hlist[i-1], hlist[i+1]))
            elif hlist[i]<=hlist[i-1] and hlist[i]<=hlist[i+1]:
                cost.append(min(hlist[i-1], hlist[i+1]) - hlist[i])
            else:
                cost.append(0)
    
    #print(cost)
    rest=k
    while rest>0:
        bango=cost.index(max(cost))
        hlist=hlist[:bango]+hlist[bango+1:]
        cost=cost[:bango]+cost[bango+1:]
        if bango==0:
            search=[bango]
        elif bango==len(hlist):
            search=[bango-1]
        else:
            search=[bango-1, bango]
        if len(hlist)>=2:
            for i in search:
                if i==0:
                    if hlist[i]>=hlist[i+1]:
                        cost[i]=hlist[i]-hlist[i+1]
                    else:
                        cost[i]=0
                elif i==len(hlist)-1:
                    if hlist[i]>=hlist[i-1]:
                        cost[i]=hlist[i]-hlist[i-1]
                    else:
                        cost[i]=0
                else:
                    if hlist[i]>=hlist[i-1] and hlist[i]>=hlist[i+1]:
                        cost[i]=hlist[i]-max(hlist[i-1], hlist[i+1])
                    elif hlist[i]<=hlist[i-1] and hlist[i]<=hlist[i+1]:
                        cost[i]=min(hlist[i-1], hlist[i+1]) - hlist[i]
                    else:
                        cost[i]=0
            rest-=1
        else:
            if rest>1:
                hlist=[0]
                break
            else:
                break
        
        #print(cost, hlist)
    
    nul=0
    mae=0
    for i in range(len(hlist)):
        if hlist[i]>=mae:
            nul+=hlist[i]-mae
        mae=hlist[i]
    print(nul)
else:
    if k>=1:
        print(0)
    else:
        print(hlist[0])

Submission status: Wrong Answer

Solution code:
import os
import sys

import numpy as np

if os.getenv("LOCAL"):
    sys.stdin = open("_in.txt", "r")

sys.setrecursionlimit(10 ** 9)
INF = float("inf")
IINF = 10 ** 18
MOD = 10 ** 9 + 7
# MOD = 998244353

N, K = list(map(int, sys.stdin.readline().split()))
H = list(map(int, sys.stdin.readline().split()))

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

H = np.array(H, dtype=float)


# @debug
def count(heights):
    H = heights.copy()
    ret = 0
    cnt = 1
    height = H.min()
    # 普通に数えてみる
    while height != np.inf:
        H -= height
        ret += cnt * height
        H[H == 0.0] = np.inf
        cnt = np.count_nonzero(np.diff((H != np.inf).astype(int)) == 1)
        cnt += H[0] != np.inf
        height = H.min()
    return int(ret)


# 上から何個変えるか、下から何個変えるかを全探索
ans = INF
orders = H.argsort()
for k in range(K + 1):
    # 下から k 個変える
    heights = H.copy()
    if k > 0:
        bottom = orders[k]
        heights[orders[:k]] = bottom
    if K - k > 0:
        top = orders[~(K - k)]
        heights[orders[~(K - k) + 1:]] = top
    ans = min(ans, count(heights))
print(ans)

Submission status: Time Limit Exceeded

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

Submission status: Time Limit Exceeded

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

Submission status: Time Limit Exceeded

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

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 and N-1-i>=K-(k+j):
                    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()