代码随想录算法训练营第五十一天| 309.最佳买卖股票时机含冷冻期,714.买卖股票的最佳时机含手续费

代码随想录算法训练营第五十一天

  • 309.最佳买卖股票时机含冷冻期
  • 714.买卖股票的最佳时机含手续费

309.最佳买卖股票时机含冷冻期

代码

#  !/usr/bin/env  python
#  -*- coding:utf-8 -*-
# @Time   :  2022.12
# @Author :  hello algorithm!
# @Note   :  https://leetcode.cn/problems/best-time-to-buy-and-sell-stock-with-cooldown/
from typing import List


class Solution:
    """
    dp[i][j]表示第i天,状态为j时,最大利润
    0. dp[i][0] 表示第i天买入,包含持有
    1. dp[i][1] 两天前就卖出了股票,度过了冷冻期,一直没操作,今天保持卖出股票状态
    2. dp[i][2] 今天卖出了股票
    3. dp[i][3] 今天为冷冻期状态
    递推公式:
    dp[i][0] = max(dp[i-1][0],dp[i-1][1]-prices[i],dp[i-1][3]-prices[i])
    dp[i][1] = max(dp[i-1][1],dp[i-1][3])
    dp[i][2] = dp[i-1][0] + prices[i]
    dp[i][3] = dp[i-1][2]
    """

    def maxProfit(self, prices: List[int]) -> int:
        dp = [[0 for _ in range(4)] for _ in range(len(prices))]
        dp[0][0] = -prices[0]
        dp[0][1] = 0
        dp[0][2] = 0
        dp[0][3] = 0
        for i in range(1, len(prices)):
            dp[i][0] = max(dp[i - 1][0], dp[i - 1][1] - prices[i], dp[i - 1][3] - prices[i])
            dp[i][1] = max(dp[i - 1][1], dp[i - 1][3])
            dp[i][2] = dp[i - 1][0] + prices[i]
            dp[i][3] = dp[i - 1][2]
        return max(dp[-1])


if __name__ == '__main__':
    s = Solution()
    prices = [1, 2, 3, 0, 2]
    print(s.maxProfit(prices))

714.买卖股票的最佳时机含手续费

代码

#  !/usr/bin/env  python
#  -*- coding:utf-8 -*-
# @Time   :  2022.12
# @Author :  hello algorithm!
# @Note   :  https://leetcode.cn/problems/best-time-to-buy-and-sell-stock-with-transaction-fee/
from typing import List


class Solution:
    """
    使用动态规划解题
    dp[i][0] 表示第i天持有股票所获得最大利润
    dp[i][1] 表示第i不持有股票所获得最大利润
    递推公式:
    dp[i][0] = max(dp[i-1][0],dp[i-1][1]-prices[i])
    dp[i][1] = max(dp[i-1][0]+prices[i]-fee,dp[i-1][1])
    """

    def maxProfit(self, prices: List[int], fee: int) -> int:
        dp = [[0 for _ in range(2)] for _ in range(len(prices))]
        dp[0][0] = -prices[0]
        dp[0][1] = 0
        for i in range(1, len(prices)):
            dp[i][0] = max(dp[i - 1][0], dp[i - 1][1] - prices[i])
            dp[i][1] = max(dp[i - 1][0] + prices[i] - fee, dp[i - 1][1])
        if dp[-1][-1] < 0:
            return 0
        return dp[-1][-1]


if __name__ == '__main__':
    prices = [1, 3, 2, 8, 4, 9]
    fee = 2
    s = Solution()
    print(s.maxProfit(prices, fee))

你可能感兴趣的:(算法,动态规划,leetcode)