leetcode123-- Best Time to Buy and Sell Stock III

leetcode123-- Best Time to Buy and Sell Stock III

题目

Say you have an array for which the ith element is the price of a given stock on day i.

Design an algorithm to find the maximum profit. You may complete at most two transactions.

Note: You may not engage in multiple transactions at the same time (i.e., you must sell the stock before you buy again).

Example 1:

Input: [3,3,5,0,0,3,1,4]
Output: 6
Explanation: Buy on day 4 (price = 0) and sell on day 6 (price = 3), profit = 3-0 = 3.
             Then buy on day 7 (price = 1) and sell on day 8 (price = 4), profit = 4-1 = 3.

Example 2:

Input: [1,2,3,4,5]
Output: 4
Explanation: Buy on day 1 (price = 1) and sell on day 5 (price = 5), profit = 5-1 = 4.
             Note that you cannot buy on day 1, buy on day 2 and sell them later, as you are
             engaging multiple transactions at the same time. You must sell before buying again.

Example 3:

Input: [7,6,4,3,1]
Output: 0
Explanation: In this case, no transaction is done, i.e. max profit = 0.

解答, 这次又更难了一些


class Solution(object):
    def maxProfit(self, prices):
        """
        :type prices: List[int]
        :rtype: int
        """
        
        # 这个规定最多交易两次,即两次买, 两次卖
        
        # local[i][j] 代表在最多进行j次交易的情况下,并且在第i天当天卖掉之后的最大利润
        # global[i][j] 代表在最多进行j次交易的情况下,第i天结束时的最大利润
        
        # 则有 l[i][j] = max(g[i-1][j-1] + max(diff, 0), l[i-1][j]+diff)
        # g[i][j] = max(l[i][j], g[i-1][j])
        
        if (len(prices)) ==0:
            return 0
        
        n = len(prices)
        
        l = [[0 for _ in range(3)] for _ in range(n)]  # n行3列
        g = [[0 for _ in range(3)] for _ in range(n)]  # n行3列
        
        for i in range(1, len(prices)):
            diff = prices[i]- prices[i-1]   # 昨天买今天卖的差值
            for j in range(1, 3):
                l[i][j] = max(g[i-1][j-1]+max(diff, 0), l[i-1][j]+diff)
                # 因为有两种情况,首先今天必段卖,所以后面的,另外是如是要diff>0的话,如果diff<0的话,就不记了,因为可能还是之前的最大
                # 注意虽然今天要卖,但是l代表的是前面这几天中最大的利润
                
                g[i][j] = max(l[i][j], g[i-1][j])  # 更新之前的最大和当前的最大
                
        return g[n-1][2]
        

打赏,谢谢~~

取消

感谢您的支持,我会继续努力的!

扫码支持
扫码打赏,多谢支持~

打开微信扫一扫,即可进行扫码打赏哦