Python实现y总上课版会TLE,需要压缩1维才能AC,注释掉的部分是保留第一维时候的写法,思想与y总上课时的基本一致,初始化和下标什么的有一点出入。
# 状态表示 集合 dp[i][j][k] 所有只走完前i支股票,且已经进行了j次交易的所有方案的集合 k=0,1表示是否持有当前股票
# 属性 max
# 状态计算 dp[i][j][0] = max(dp[i - 1][j][0], dp[i - 1][j - 1][1] + w[i])
# dp[i][j][1] = max(dp[i - 1][j][1], dp[i - 1][j][0] - w[i])
n, m = list(map(int, input().split()))
w = list(map(int, input().split()))
# dp = [[[float('-inf')] * 2 for _ in range(m + 1)] for _ in range(n + 1)]
dp = [[float('-inf')] * 2 for _ in range(m + 1)]
# for i in range(n + 1):
# dp[i][0][0] = 0
# for j in range(m + 1):
# dp[0][j][0] = 0
for j in range(m + 1):
dp[j][0] = 0
for i in range(1, n + 1):
for j in range(m, -1, -1):
if j > 0:
dp[j][0] = max(dp[j][0], dp[j - 1][1] + w[i - 1])
dp[j][1] = max(dp[j][1], dp[j][0] - w[i - 1])
# for j in range(0, m + 1):
# if j > 0:
# dp[i][j][0] = max(dp[i - 1][j][0], dp[i - 1][j - 1][1] + w[i - 1])
# dp[i][j][1] = max(dp[i - 1][j][1], dp[i - 1][j][0] - w[i - 1])
res = 0
for j in range(m + 1):
res = max(dp[j][0], res)
print(res)
Y总初始化法
# 状态DP
# 状态表示 f[i][j][k] 集合 所有只走完前i支股票,且已经进行了j次交易的所有方案的集合
# 属性 当前最大收益 max(f[n][0:k][0])
# 状态计算 f[i][j][0] = max(f[i - 1][j][0], f[i - 1][j - 1][1] + w[i])
# f[i][j][1] = max(f[i - 1][j][1], f[i - 1][j][0] - w[i])
n, k = list(map(int, input().split()))
w = [0] + list(map(int, input().split()))
# f = [[[float('-inf')] * 2 for _ in range(k + 1)] for _ in range(n + 1)]
# f[0][0][0] = 0
f = [[float('-inf')] * 2 for _ in range(k + 1)]
f[0][0] = 0
for i in range(1, n + 1):
# for j in range(0, k + 1):
# f[i][j][0] = f[i - 1][j][0]
# if j > 0:
# f[i][j][0] = max(f[i - 1][j][0], f[i - 1][j - 1][1] + w[i])
# f[i][j][1] = max(f[i - 1][j][1], f[i - 1][j][0] - w[i])
for j in range(k, -1, -1):
if j > 0:
f[j][0] = max(f[j][0], f[j - 1][1] + w[i])
f[j][1] = max(f[j][1], f[j][0] - w[i])
res = 0
for j in range(k + 1):
res = max(res, f[j][0])
print(res)