刷题第四十三天 309.买卖股票最佳时机+冷冻 714. 买卖股票最佳时机+手续费

2023-12-14 10:53:58

class Solution:
    def maxProfit(self, prices: List[int]) -> int:
        #dp[i][0] 第i天持有股票 手上的最大现金
        #dp[i][1] 第i天不持有股票,手上的最大现金
        #dp[i][0] = max(dp[i - 1][0], dp[i - 2][1] - prices[i]) 因为有一天冻结,并且无限次交易,所以第i天持有的情况之一 就是第i-2天的时候卖掉的时候手上的现金 减掉今天的价格
        #dp[i][1] = max(dp[i - 1][1], dp[i - 1][0] + prices[i]) 不持有的情况不影响,因为出售没有冷冻限制
        if len(prices) == 1:
            return 0
        if len(prices) == 2:
            return (prices[1] - prices[0]) if prices[1] - prices[0] > 0 else 0
        dp = [[0] * 2 for _ in range(len(prices))]
        dp[0][0] = -prices[0]

        for i in range(1, len(prices)):
            if i == 1:
                dp[i][0] = max(dp[i - 1][0], dp[i - 1][1] - prices[i])
                dp[i][1] = max(dp[i - 1][1], dp[i - 1][0] + prices[i])    
            dp[i][0] = max(dp[i - 1][0], dp[i - 2][1] - prices[i])
            dp[i][1] = max(dp[i - 1][1], dp[i - 1][0] + prices[i])            
        return dp[-1][1]

#dp[i][0] 第i天持有股票 手上的最大现金

#dp[i][1] 第i天不持有股票,手上的最大现金

#dp[i][0] = max(dp[i - 1][0], dp[i - 2][1] - prices[i]) 因为有一天冻结,并且无限次交易,所以第i天持有的情况之一 就是第i-2天的时候卖掉的时候手上的现金 减掉今天的价格

#dp[i][1] = max(dp[i - 1][1], dp[i - 1][0] + prices[i]) 不持有的情况不影响,因为出售没有冷冻限制

class Solution:
    def maxProfit(self, prices: List[int], fee: int) -> int:
        #dp[i][0] 第i天持有股票 手上的最大现金
        #dp[i][1] 第i天不持有股票,手上的最大现金
        #dp[i][0] = max(dp[i - 1][0], dp[i - 1][1] - prices[i] - fee)  #因为每笔交易,所以统一在买入的时候收,涉及到买卖就再减掉fee
        #dp[i][1] = max(dp[i - 1][1], dp[i - 1][0] + prices[i])
        if len(prices) == 1:
            return 0
        if len(prices) == 2:
            return (prices[1] - prices[0] - fee) if prices[1] - prices[0] - fee > 0 else 0
        dp = [[0] * 2 for _ in range(len(prices))]
        dp[0][0] = -prices[0] - fee

        for i in range(1, len(prices)):
            dp[i][0] = max(dp[i - 1][0], dp[i - 1][1] - prices[i] - fee)
            dp[i][1] = max(dp[i - 1][1], dp[i - 1][0] + prices[i])            
        return dp[-1][1]

#dp[i][0] 第i天持有股票 手上的最大现金
#dp[i][1] 第i天不持有股票,手上的最大现金
#dp[i][0] = max(dp[i - 1][0], dp[i - 1][1] - prices[i] - fee) ?#因为每笔交易,所以统一在买入的时候收,涉及到买卖就再减掉fee
#dp[i][1] = max(dp[i - 1][1], dp[i - 1][0] + prices[i])

总结篇代码随想录

文章来源:https://blog.csdn.net/qq_43211720/article/details/134987822
本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。