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:
#!/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
            if nd[(h[i], b)] > value + (h[i] - a if h[i] > a else 0):
                nd[(h[i], b)] = value + (h[i] - a if h[i] > a else 0)
            if b + 1 > k:
                continue
            if nd[(a, b + 1)] > value:
                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: 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()

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

for x in range(N):
    for y in range(N-K+1):
        if x+1<y:
            continue
        elif y==0:
            dp[x][y] = float('inf')
        elif y==1:
            dp[x][y] = H[x]
        else:
            val = float('inf')
            for i in range(x):
                now = dp[i][y-1] + max(0,H[x]-H[i])
                if now<val:
                    val = now
            dp[x][y] = val

ans = float('inf')
for i in range(N):
    if dp[i][N-K]<ans:
        ans = dp[i][N-K]

print(ans)

Submission status: Wrong Answer

Solution code:
def main():
    from collections import Counter
    n,k=map(int,input().split())
    h=list(map(int,input().split()))
    def check(a):
        return a[len(a)-1]+sum([a[i]-a[i+1] for i in range(len(a)-1) if a[i]>a[i+1]])
    dp=[[10**13,[]] for i in [0]*(k+1)]
    dp[0][0]=0
    for c in range(n):
        dp2=[[10**13,[]]*2 for i in [0]*(k+1)]
        for i in range(k+1):
            temp=check(dp[i][1]+[h[c]])
            if dp2[i][0]>temp:
                dp2[i][0]=temp
                dp2[i][1]=[t for t in dp[i][1]]+[h[c]]
        for i in range(k):
            if dp2[i+1][0]>dp[i][0]:
                dp2[i+1][0]=dp[i][0]
                dp2[i+1][1]=[t for t in dp[i][1]]
        dp=dp2
    m=10**13
    for i in range(k+1):
        m=min(m,dp[i][0])
    print(m)
main()

Submission status: Wrong Answer

Solution code:

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


class Union_Find():
	def __init__(self, n):
		self.union = [i for i in range(n)]
		self.level = [0 for i in range(n)]

	def root(self, i, mode=0):
		keiro = [i]
		ans = i
		while ans != self.union[ans]:
			ans = self.union[ans]
			keiro.append(ans)
		if mode == 0:
			return ans
		else:
			return ans, keiro

	def unite(self, i, j):
		root_i, list_i = self.root(i, 1)
		root_j, list_j = self.root(j, 1)
		if root_i != root_j:
			if self.level[root_i] < self.level[root_j]:
				self.level[root_j] = max(self.level[root_i] + 1, self.level[root_j])
				for node in list_i:
					self.union[node] = root_j
			else:
				self.level[root_i] = max(self.level[root_j] + 1, self.level[root_i])
				for node in list_j:
					self.union[node] = root_i


N, T = list(map(int, input().split()))

H = [0]

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

H.append(0)

UF = Union_Find(N + 2)
for i in range(1, N):
	if H[i] == H[i + 1]:
		UF.unite(i, i + 1)


for t in range(T):
	max_diff = 0
	max_next = -1
	max_next_next = -1
	for i in range(1, N + 1):
		if UF.root(i) != i:
			continue
		base = i + 1
		while True:
			if UF.root(base) != i or base == N + 1:
				right = base
				break
			else:
				base += 1
		base = i - 1
		while True:
			if UF.root(base) != i or base == 0:
				left = base
				break
			else:
				base -= 1
		diff = min(abs(H[i] - H[right]), abs(H[i] - H[left]))
		if (H[i] - H[right])*(H[i] - H[left]) < 0:
			continue
		if diff >= max_diff:
			max_diff = diff
			max_next = i
			if abs(H[i] - H[right]) < abs(H[i] - H[left]):
				max_next_next = right
			else:
				max_next_next = left
	UF.unite(max_next, max_next_next)
	_, keiro = UF.root(max_next, mode=1)
	for num in keiro:
		H[num] = H[max_next_next]

for i in range(1, N + 1):
	H[i] = H[UF.root(i)]

length_list = set()
for i in range(1, N + 1):
	if i == UF.root(i):
		length_list.add(H[i])
length_list = list(length_list)
length_list.sort()

sum = 0
before_length = 0
for length in length_list:
	sum_part = 0
	num_disjoin = 0
	for i in range(1, N + 1):
		if H[i] >= length and H[i - 1] < length:
			sum_part += 1

	sum += sum_part*(length - before_length)
	before_length = length

print(sum)

Submission status: Wrong Answer

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:
    startVal = -1
    for idx in range(len(h)):
        if h[idx]>0:
            if startVal < 0:
                startVal = idx
        else:
            if startVal >= 0:
                drawrank = min(h[startVal:idx])
                for didx in range(startVal, idx):
                    h[didx] -= drawrank
                cnt += drawrank
                startVal = -1
    
    if startVal >= 0:
        drawrank = min(h[startVal:idx+1])
        for didx in range(startVal, idx+1):
            h[didx] -= drawrank
        cnt += drawrank
print(cnt)

Submission status: Wrong Answer

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

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


H2 = list(enumerate(H))
H2.sort(key=lambda x:x[1])
for _ in [0]*K:
    H2.pop()
H2.sort(key=lambda x:x[0])
H3 = [h[1] for h in H2]

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

ans = f(H3)
print(ans)

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()
    n += 2
    h.insert(0,0)
    h.append(0)
    f = [0]*n
    l = [i for i in range(n)]
    for i in range(k):
        a = 0
        p = 0
        for j in range(1,n-1-k):
            if h[l[j-1]] < h[l[j]] and h[l[j+1]] < h[l[j]]:
                if a < h[l[j]]-h[l[j-1]]:
                    p = j
                    a = h[l[j]]-h[l[j-1]]
        f[l[p]] = 1
        l.pop(p)
    ans = 0
    l = 0
    for i in range(1,n):
        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:
import sys
N, K = map(int, input().split())
H = list(map(int, input().split()))
if N<=K:
    print(0)
    sys.exit()
dp = [[[float('inf')]*(K+2) for i in range(N+2)] for j in range(N+1)]
dp[0][0][0] = H[0]
dp[0][-1][1] = 0
for i in range(N-1):
    for j in range(i+1):
        for k in range(K+1):
            if H[j]>H[i+1]:
                dp[i+1][i+1][k] = min(dp[i][j][k], dp[i+1][i+1][k])
            else:
                dp[i+1][i+1][k] = min(dp[i+1][i+1][k], dp[i][j][k]+H[i+1]-H[j])
                dp[i+1][j][k+1] = min(dp[i][j][k], dp[i+1][j][k+1])
    for k in range(K):
        dp[i+1][-1][k+1] = min(dp[i][-1][k], dp[i+1][-1][k+1])
        dp[i+1][i+1][k] = min(dp[i+1][i+1][k], dp[i][-1][k]+H[i+1])

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

Submission status: Wrong Answer

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

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

    if N == K:
        return 0

    # 最初に変更しないkを全探索する
    ans = INF
    for k in range(N):
        if k > K: continue
        dp = [[INF]*(K+1) for _ in range(N)]
        dp[k][k] = Hs[k]
        for i in range(k+1, N):
            # 今回変更しない
            d = max(0, Hs[i] - Hs[i-1])
            for j in range(K+1):
                dp[i][j] = min(dp[i][j], dp[i-1][j] + d)
            # 今回変更する
            for j in range(1, K+1):
                dp[i][j] = min(dp[i][j], dp[i-1][j-1])
            if Hs[i] <= Hs[i+1]:
                for j in range(1, K+1):
                    dp[i][j] = min(dp[i][j], dp[i-1][j])
        num = min(dp[N-1])
        ans = min(ans, num)

    return ans

ans = solve()
print(ans)

Submission status: Wrong Answer

Solution code:
n,k = map(int,input().split())
lis = list(map(int,input().split()))
num = 0
for nu in lis:
    if nu != 0:
        num += 1
if num <= k:
    print(0)
    exit()
cnt = [0 for i in range(n)]
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))
    cnt[numm] = 1
    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])
nn = 10 ** 10
for i in range(n):
    if cnt[i] == 1:
        nn = min(nn,lis[i])
for i in range(n):
    if cnt[i] == 1:
        lis[i] = nn
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:
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)
for i in range(min(n,k+10)):
    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))
r = range(n)

#print(hhh)
#cnt = 0

while time.time() - ti < 0.7:
    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)

while True:
    tank = set(random.sample(r,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())
lis = list(map(int,input().split()))
num = 0
for nu in lis:
    if nu != 0:
        num += 1
if num <= k:
    print(0)
    exit()
cnt = [0 for i in range(n)]
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))
    cnt[numm] = 1
    if numm == 0:
        lis[0] = 1
    elif numm == n-1:
        lis[n-1] = 1
    else:
        lis[numm] = min(lis[numm-1],lis[numm+1])
nn = 10 ** 10
for i in range(n):
    if cnt[i] == 1:
        nn = min(nn,lis[i])
for i in range(n):
    if cnt[i] == 1:
        lis[i] = nn
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:
import sys
N, K = map(int, input().split())
H = list(map(int, input().split()))
if N<=K:
    print(0)
    sys.exit()
dp = [[[float('inf')]*(K+2) for i in range(N+2)] for j in range(N+1)]
dp[0][0][0] = H[0]
dp[0][N][1] = 0
for i in range(N-1):
    for j in range(i+1):
        for k in range(K+1):
            if H[j]>H[i+1]:
                dp[i+1][i+1][k] = min(dp[i][j][k], dp[i+1][i+1][k])
            else:
                dp[i+1][i+1][k] = min(dp[i+1][i+1][k], dp[i][j][k]+H[i+1]-H[j])
                dp[i+1][j][k+1] = min(dp[i][j][k], dp[i+1][j][k+1])
ans = float('inf')
for i in range(K+1):
    res = min(dp[N-1][j][i] for j in range(N))
    ans = min(ans, res)
print(ans)

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()
cnt = [0 for i in range(n)]
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))
    cnt[numm] = 1
    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])
nn = 10 ** 10
for i in range(n):
    if cnt[i] == 1:
        nn = min(nn,lis[i])
for i in range(n):
    if cnt[i] == 1:
        lis[i] = nn
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:
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()
cnt = [0 for i in range(n)]
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))
    cnt[numm] = 1
    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])
nn = 10 ** 10
for i in range(n):
    if cnt[i] == 1:
        nn = min(nn,cnt[i])
for i in range(n):
    if cnt[i] == 1:
        lis[i] = nn    
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:
import sys
input = sys.stdin.readline
import copy

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

if K>=N:
    print(0)
    sys.exit()

L=sorted(H)


def score(H,i):
    if H==[]:
        return 0
    
    MIN=min(H)
    x=H.index(MIN)

    return MIN-i+score(H[:x],MIN)+score(H[x+1:],MIN)

J=[(h,ind) for ind,h in enumerate(H)]
J.sort(reverse=True)

ANS=1<<60

for l in L:
    H2=copy.deepcopy(H)
    for k in range(K):
        H2[J[k][1]]=l

    ANS=min(ANS,score(H2,0))

print(ANS)

Submission status: Wrong Answer

Solution code:
N,K=map(int,input().split())
H=list(map(int,input().split()))
def f(H):
    x,y=0,0
    for h in H:
        if h>y:
            x+=h-y
        y=h
    return x
dp=[(f(H),H)]+[(0,[])]*K
for i in range(1,K+1):
    x,y=dp[i-1]
    for j in range(len(dp[i-1][1])):
        z=f(dp[i-1][1][:j]+dp[i-1][1][j+1:])
        if z<x:
            x,y=z,dp[i-1][1][:j]+dp[i-1][1][j+1:]
    dp[i]=x,y
print(dp[-1][0])

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
    muki = [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])
                muki[i] = 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])
                muki[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,muki

for k in range(K):
    x,muki = calc(H)
    maxi = -1
    maxval = -1
    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:
            if muki[i]==1:
                H[maxi] = min(H[maxi-1], H[maxi+1])
            if muki[i]==-1:
                H[maxi] = max(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)
for i in range(min(n,k+10)):
    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))
r = range(n)

#print(hhh)
#cnt = 0

while time.time() - ti < 1.0:
    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)

while True:
    tank = set(random.sample(r,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 = list(map(int, input().split()))
hs = [0] + list(map(int, input().split())) + [0]

#print(hs)
for _ in range(k):
	dif = []
	for i in range(1, len(hs) - 1):
		dif.append(abs(hs[i] - hs[i - 1]) + abs(hs[i + 1] - hs[i]))
	hs.pop(dif.index(max(dif)) + 1)

dif = []
#print(hs)
for i in range(1, len(hs)):
	dif.append(max(hs[i] - hs[i - 1], 0))
print(sum(dif))

Submission status: Wrong Answer

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

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

    if N == K:
        return 0

    # 最初に変更しないkを全探索する
    ans = INF
    for k in range(N):
        if k > K: continue
        dp = [[INF]*(K+1) for _ in range(N)]
        dp[k][k] = Hs[k]
        for i in range(k+1, N):
            # 今回変更しない
            d = max(0, Hs[i] - Hs[i-1])
            for j in range(K+1):
                dp[i][j] = min(dp[i][j], dp[i-1][j] + d)
            # 今回変更する
            if Hs[i] > Hs[i+1]:
                for j in range(1, K+1):
                    dp[i][j] = min(dp[i][j], dp[i-1][j-1])
            else:
                for j in range(1, K+1):
                    dp[i][j] = min(dp[i][j], dp[i-1][j])
        num = min(dp[N-1])
        ans = min(ans, num)

    return ans

ans = solve()
print(ans)

Submission status: Wrong Answer

Solution code:
x, y = map(int, input().split())
if x == y and x % 3 != 0:
	print(0)
else:
	if x == (2 * y) or y == (2 * x):
		print(1)
	else:
		if x == y and x % 3 == 0:
			print((2**(x - 2)) % 1000000007)
		else:
			m = min(x, y)
			n = m - (m % 3)
			print((2**(n - 2) + (m % 3) + 1) % 1000000007)

Submission status: Wrong Answer

Solution code:
import heapq


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

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


lis = []


for j in range(K):

    smin = float("inf")

    for i in range(len(H)-1):
        if H[i] > H[i-1] and H[i] > H[i+1] and smin > min(H[i]-H[i-1],H[i]-H[i+1]):
            smin = i
            sm = min(H[i]-H[i-1],H[i]-H[i+1])

    nh = []

    for i in range(len(H)-1):
        if i != smin:
            nh.append(H[i])

    nh.append(0)
    H = nh.copy()     
ans = 0

for i in range(len(H)):

    if H[i] > H[i-1]:
        ans += H[i] - H[i-1]

print (ans)

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
            
        
    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]
    before = inf
    for i in range(N):
        if i>K:
            break
        dp[i][i][1] = min(before,H[i])
        before = min(before,H[i])
    for i in range(1,N):
        for k in range(K+1):
            if k >= 1:
                dp[i][k][1] = min(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:
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
    muki = [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])
                muki[i] = 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])
                muki[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,muki

for k in range(K):
    x,muki = calc(H)
    maxi = -1
    maxval = -1
    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:
            if muki[i]==1:
                H[maxi] = min(H[maxi-1], H[maxi+1])
            if muki[i]==-1:
                H[maxi] = max(H[maxi-1], H[maxi+1])
            ans -= x[maxi]

print(ans)

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
            
        
    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]
    before = inf
    for i in range(N):
        if i>K:
            break
        dp[i][i][1] = min(before,H[i])
    for i in range(1,N):
        for k in range(K+1):
            if k >= 1:
                dp[i][k][1] = min(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:
def solve():
    INF = float('inf')

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

    # 最初に変更しないkを全探索する
    ans = INF
    for k in range(N):
        if k > K: continue
        dp = [[INF]*(K+1) for _ in range(N)]
        dp[k][k] = Hs[k]
        for i in range(k+1, N):
            # 今回変更しない
            d = max(0, Hs[i] - Hs[i-1])
            for j in range(K+1):
                dp[i][j] = min(dp[i][j], dp[i-1][j] + d)
            # 今回変更する
            if Hs[i] > Hs[i+1]:
                for j in range(1, K+1):
                    dp[i][j] = min(dp[i][j], dp[i-1][j-1])
            else:
                for j in range(1, K+1):
                    dp[i][j] = min(dp[i][j], dp[i-1][j])
        num = min(dp[N-1])
        ans = min(ans, num)

    print(ans)

solve()