Python版-LeetCode 学习:买卖股票的最佳时机(121,122,123,188,309,714)

  1. 买卖股票的最佳时机 交易次数K=1 

给定一个数组,它的第 i 个元素是一支给定股票第 i 天的价格。如果你最多只允许完成一笔交易(即买入和卖出一支股票一次),设计一个算法来计算你所能获取的最大利润。注意:你不能在买入股票前卖出股票。

示例 1:    输入: [7,1,5,3,6,4]  输出: 5
解释: 在第 2 天(股票价格 = 1)的时候买入,在第 5 天(股票价格 = 6)的时候卖出,最大利润 = 6-1 = 5 。
     注意利润不能是 7-1 = 6, 因为卖出价格需要大于买入价格;同时,你不能在买入前卖出股票。

来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/best-time-to-buy-and-sell-stock

方法1:

class Solution:
    def maxProfit(self, prices: List[int]) -> int:
        result, buy = 0, float('inf')
        for price in prices:
            if buy > price:
                buy = price
            # 寻找价差最大的那个值
            if result < price - buy:
                result = price - buy

        return result

方法2:利用动态规划的思想来考虑

class Solution:
    def maxProfit(self, prices: List[int]) -> int:
        if prices ==[]: return 0
        n=len(prices)
        
        dp_0,dp_1=0,float('-inf')
        for i in  range(n):
            # 今天我没有持有股票,有两种可能:
            # 要么是我昨天就没有持有,然后今天选择 rest,所以我今天还是没有持有;
            # 要么是我昨天持有股票,但是今天我 sell 了,所以我今天没有持有股票了。
            dp_0=max(dp_0, dp_1+prices[i])
            # 解释:今天我持有着股票,有两种可能:
            # 要么我昨天就持有着股票,然后今天选择 rest,所以我今天还持有着股票;
            # 要么我昨天本没有持有,但今天我选择 buy,所以今天我就持有股票了。
            dp_1=max(dp_1,-prices[i])
            
        return dp_0

2.交易次数K=+infinity

设计一个算法来计算你所能获取的最大利润。你可以尽可能地完成更多的交易(多次买卖一支股票)。

注意:你不能同时参与多笔交易(你必须在再次购买前出售掉之前的股票)。

来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/best-time-to-buy-and-sell-stock-ii

方法1: 

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

方法2:

class Solution:
    def maxProfit(self, prices: List[int]) -> int:
        dp_0,dp_1=0,float('-inf')
        for price in prices:
            # 
            tmp=dp_0
            # 
            dp_0=max(dp_0,dp_1+price)
            dp_1=max(dp_1,tmp-price)
        return dp_0

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

给定一个整数数组,其中第 i 个元素代表了第 i 天的股票价格 。​设计一个算法计算出最大利润。在满足以下约束条件下,你可以尽可能地完成更多的交易(多次买卖一支股票):你不能同时参与多笔交易(你必须在再次购买前出售掉之前的股票)。
卖出股票后,你无法在第二天买入股票 (即冷冻期为 1 天)。

示例:   输入: [1,2,3,0,2] 输出: 3 解释: 对应的交易状态为: [买入, 卖出, 冷冻期, 买入, 卖出]

来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/best-time-to-buy-and-sell-stock-with-cooldown

方法1:

class Solution:
    def maxProfit(self, prices: List[int]) -> int:
        if not prices:
            return 0
        n = len(prices)
        # f[i][0]: 手上持有股票的最大收益
        # f[i][1]: 手上不持有股票,并且处于冷冻期中的累计最大收益
        # f[i][2]: 手上不持有股票,并且不在冷冻期中的累计最大收益
        f = [[-prices[0], 0, 0]] + [[0] * 3 for _ in range(n - 1)]
        for i in range(1, n):
            f[i][0] = max(f[i - 1][0], f[i - 1][2] - prices[i])
            f[i][1] = f[i - 1][0] + prices[i]
            f[i][2] = max(f[i - 1][1], f[i - 1][2])
        
        return max(f[n - 1][1], f[n - 1][2])

方法2:

class Solution:
    def maxProfit(self, prices: List[int]) -> int:
        dp_0,dp_1=0,float('-inf')
        # 没有持有的前一天的卖出状态
        dp_pre_0=0

        for p in prices:
            tmp=dp_0   # 卖出值

            dp_0=max(dp_0,dp_1+p)   # 卖出阶段
            # 比较继续持有,前一天卖出值减去p的总值
            dp_1=max(dp_1,dp_pre_0-p)   # 持有阶段
            # 获取卖出值,作为前一天卖出操作值
            dp_pre_0=tmp

        return dp_0

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

给定一个整数数组 prices,其中第 i 个元素代表了第 i 天的股票价格 ;非负整数 fee 代表了交易股票的手续费用。

你可以无限次地完成交易,但是你每笔交易都需要付手续费。如果你已经购买了一个股票,在卖出它之前你就不能再继续购买股票了。返回获得利润的最大值。

注意:这里的一笔交易指买入持有并卖出股票的整个过程,每笔交易你只需要为支付一次手续费。

来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/best-time-to-buy-and-sell-stock-with-transaction-fee
方法1:

class Solution:
    def maxProfit(self, prices: List[int], fee: int) -> int:

        dp_0,dp_1=0,float('-inf')

        for p in prices:
            tmp=dp_0  # 昨天卖出后获得的利润
            dp_0=max(dp_0,dp_1+p-fee)  # 今天卖出状态下的利润
            dp_1=max(dp_1,dp_0-p)      # 今天持有状态下的利润;
            # dp_0-p,是前天卖出后,今天买入下的利润状态

        return dp_0

方法2:

class Solution:
    def maxProfit(self, prices: list, fee: int) -> int:
        if len(prices) < 2:
            return 0
        profit = 0
        buy = sold = prices[0]
        for price in prices[1:]:
            if price > sold:
                sold = price
            else:
                gain = sold - buy - fee
                if gain >0 and gain > price-buy:
                    profit += gain
                    buy = sold = price
                elif price < buy:
                    buy = sold = price
        if sold - buy > fee:
            profit += sold - buy - fee
        return profit

 123. 买卖股票的最佳时机 III  ,交易次数K=2

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

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

来源:力扣(LeetCode)链接:https://leetcode-cn.com/problems/best-time-to-buy-and-sell-stock-iii
方法1:

class Solution:
    def maxProfit(self, prices: List[int]) -> int:
        # 一次交易,初始化
        dp_i10,dp_i11=0,float('-inf')
        # 第二次交易初始化
        dp_i20,dp_i21=0,float('-inf')

        for p in prices:
            # 第二次卖出,第二次卖出的时候就是最后的总利润值,
            # 最后的利润等于,这次买入后的利润(dp_i20)加上目前的价格
            dp_i20=max(dp_i20,dp_i21+p)
            # 第二次买入,第一次卖出获得的利润减去当前价格,与上次的计算第二次买入利润相比较
            dp_i21=max(dp_i21,dp_i10-p)
            # 第一次卖出,第一次买入的利润加p,与上次的第一次买入进行利润比较
            dp_i10=max(dp_i10,dp_i11+p)
            # 第一次买入,第一次的买入与-价格p比较
            dp_i11=max(dp_i11,-p)
        return dp_i20

方法2:

 n = len(prices)
        if n < 2:
            return 0
        
        # 维护两个数组,从左到右,从右到左 找出最大利润的两笔交易
        left = [0] * n
        min_p = prices[0]
        max_p = 0
        # 第i天的最大利润 = max(第i-1天的利润,第i天的价格 - 第i-1天内最小价格)
        for i in range(1, n):
            max_p = max(max_p, prices[i] - min_p)
            min_p = min(min_p, prices[i])
            left[i] = max_p
        # print(left)

        # 第i天的最大利润 = max()
        right = [0] * n
        min_p = prices[-1]
        max_p = 0
        # 注意这里要从倒数第二天开始遍历 n-2天 n = 8 
        for i in range(n-2, -1, -1):
            # 倒序第6天的最大收益 = max(第7天的最大收益, 前7天的最大价格 - 第6天的价格)
            max_p = max(max_p, min_p - prices[i])
            min_p = max(min_p, prices[i])
            right[i] = max_p + left[i]
        
        return max(right)

188. 买卖股票的最佳时机 IV  ,交易次数K= 任意 int 

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

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

来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/best-time-to-buy-and-sell-stock-iv

方法1:

class Solution:
    def maxProfit(self, k: int, prices: List[int]) -> int:
        n=len(prices)
        if k > n/2:
            dp_0,dp_1=0,float('-inf')
            for p in prices:
                tmp=dp_0
                dp_0=max(dp_0,dp_1+p)
                dp_1=max(dp_1,tmp-p)
            return dp_0
        else:
            dp=[[[0,0] for i in range(k+1)] for i in range(len(prices))]

            for i,p in enumerate(prices):

                for k in range(1,k+1):
                    if i==0:
                        dp[i][k][0]=0
                        dp[i][k][1]=-p
                        continue
                    # 第i天的第k次操作的卖出状态,
                    dp[i][k][0]=max(dp[i-1][k][0],dp[i-1][k][1]+p)
                    dp[i][k][1]=max(dp[i-1][k][1],dp[i-1][k-1][0]-p)
            # print(dp)
            return dp[n-1][k][0]

猜你喜欢

转载自blog.csdn.net/guyu1003/article/details/107447017