代码随想录算法训练营第四十九天| 121. 买卖股票的最佳时机,122.买卖股票的最佳时机II

代码随想录算法训练营第四十九天

  • 121. 买卖股票的最佳时机
  • 122.买卖股票的最佳时机II

121. 买卖股票的最佳时机

代码

#  !/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/
from typing import List


class Solution:
    def maxProfit(self, prices: List[int]) -> int:
        max_profit = -1
        min_price = prices[0]
        for i in range(1, len(prices)):
            max_profit = max(max_profit, prices[i] - min_price)
            if min_price > prices[i]:
                min_price = prices[i]

        if max_profit < 0:
            return 0
        return max_profit


if __name__ == '__main__':
    prices = [7, 1, 5, 3, 6, 4]
    s = Solution()
    print(s.maxProfit(prices))

122.买卖股票的最佳时机II

代码

#  !/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-ii/
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],dp[i-1][1])
    """

    def maxProfit(self, prices: List[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], dp[i - 1][1])
        if dp[-1][-1] < 0:
            return 0
        return dp[-1][-1]


if __name__ == '__main__':
    prices = [7, 6, 4, 3, 1]
    s = Solution()
    print(s.maxProfit(prices))

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