leetcode188-- Best Time to Buy and Sell Stock IV

leetcode188-- Best Time to Buy and Sell Stock IV

题目

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 k transactions.

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

Example 1:

Input: [2,4,1], k = 2
Output: 2
Explanation: Buy on day 1 (price = 2) and sell on day 2 (price = 4), profit = 4-2 = 2.

Example 2:

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

然后 将之前的第三次的时候的2换成k就可以了,就是用的空间大了一些



class Solution(object):
    def maxProfit(self, k, prices):
        """
        :type k: int
        :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(k+1)] for _ in range(n)]   # n行k+1列
        g = [[0 for _ in range(k+1)] for _ in range(n)]   # n行k+1列
        
        for i in range(1, len(prices)):
            diff = prices[i]- prices[i-1]   # 昨天买今天卖的差值
            for j in range(1, k+1):
                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][k]
        

打赏,谢谢~~

取消

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

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

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