买卖股票的最佳时机 IV ——动态规划-股票收益问题

"""
188. 买卖股票的最佳时机 IV
给定一个整数数组 prices ,它的第 i 个元素 prices[i] 是一支给定的股票在第 i 天的价格。
设计一个算法来计算你所能获取的最大利润。你最多可以完成 k 笔交易。
注意:你不能同时参与多笔交易(你必须在再次购买前出售掉之前的股票)。

示例 1:
输入:k = 2, prices = [2,4,1]
输出:2
解释:在第 1 天 (股票价格 = 2) 的时候买入,在第 2 天 (股票价格 = 4) 的时候卖出,这笔交易所能获得利润 = 4-2 = 2 。
示例 2:
输入:k = 2, prices = [3,2,6,5,0,3]
输出:7
解释:在第 2 天 (股票价格 = 2) 的时候买入,在第 3 天 (股票价格 = 6) 的时候卖出, 这笔交易所能获得利润 = 6-2 = 4 。
随后,在第 5 天 (股票价格 = 0) 的时候买入,在第 6 天 (股票价格 = 3) 的时候卖出, 这笔交易所能获得利润 = 3-0 = 3 。
"""


"""
这个需要根据len(prices)和k的大小进行分别处理, 当k>len(prices)/2时,则认为k为无穷大的情况
"""
class Solution(object):
def maxProfit(self, k, prices):
"""
:type k: int
:type prices: List[int]
:rtype: int
"""
n = len(prices)
if n < 1: return 0
if k >= n/2:
# k被认为无穷大的情况
return self.maxProfitOnInf(prices)
dp = [[[0 for _ in range(2)] for _ in range(k + 1)] for _ in range(n)]

for i in range(n):
dp[i][0][0] = 0
dp[i][0][1] = - float('inf')

for k in range(1, k + 1):
dp[0][k][0] = 0
dp[0][k][1] = -prices[0] # 之前写成了prices[i] 导致一致没有AC

for i in range(1, n):
for j in range(1, k + 1):
dp[i][j][0] = max(dp[i - 1][j][0], dp[i - 1][j][1] + prices[i])
dp[i][j][1] = max(dp[i - 1][j][1], dp[i - 1][j - 1][0] - prices[i])
return dp[n - 1][k][0]


def maxProfitOnInf(self, prices):
dp_i_0 = 0
dp_i_1 = -float('inf')

n = len(prices)
for i in range(n):
tmp = dp_i_0
dp_i_0 = max(dp_i_0, dp_i_1 + prices[i])
dp_i_1 = max(dp_i_1, tmp - prices[i])
return dp_i_0


if __name__ == "__main__":
k = 2
prices = [3, 2, 6, 5, 0, 3]
res = Solution().maxProfit(k, prices)
print(res)

上一篇:1510. 石子游戏 IV SG定理即可


下一篇:Android动画之属性动画,阿里巴巴开发规范手册