Leetcode 188. 买卖股票的最佳时机 IV(Python3)

188. 买卖股票的最佳时机 IV

给定一个数组,它的第 i 个元素是一支给定的股票在第 天的价格。

设计一个算法来计算你所能获取的最大利润。你最多可以完成 k 笔交易。

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

示例 1:

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

示例 2:

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

自己的代码:对123的DP答案进行扩展,结果TLE,仅供参考思路。

import sys
class Solution(object):
    def maxProfit(self, k, prices):
        """
        :type k: int
        :type prices: List[int]
        :rtype: int
        """
        if not prices or not k: return 0
        mp = [[[0,0]for _ in range(k+1)]for _ in range(len(prices))]
        mp[0][0][0],mp[0][0][1] = 0,-prices[0]
        for i in range(1,k+1):
            mp[0][i][0],mp[0][i][1] = -sys.maxsize,-sys.maxsize
        for i in range(1,len(prices)):
            mp[i][0][0] = mp[i-1][0][0]
            mp[i][0][1] = max(mp[i-1][0][1],mp[i-1][0][0]-prices[i])
            for j in range(1,k):
                mp[i][j][0] = max(mp[i - 1][j][0], mp[i - 1][j-1][1] + prices[i])
                mp[i][j][1] = max(mp[i - 1][j][1], mp[i - 1][j][0] - prices[i])
            mp[i][k][0] = max(mp[i - 1][k][0], mp[i - 1][k-1][1] + prices[i])

        return max(mp[len(prices) - 1][i][0] for i in range(k+1))

优化:参考答案出处 here

class Solution(object):
    def maxProfit(self, k, prices):
        l =  len(prices)
        if k >= l / 2:return self.greedy(prices)
        mp = [[0 for _ in range(l)]for _ in range(k+1)]
        for i in range(1,k+1):
            Max = -prices[0]
            for j in range(1,l):
                mp[i][j] = max(mp[i][j-1],prices[j]+Max)
                Max = max(Max,mp[i-1][j-1]-prices[j])
        return mp[-1][-1]
    def greedy(self,prices):
        mp = 0
        for i in range(1,len(prices)):
            if prices[i] > prices[i-1]:mp += prices[i] - prices[i-1]
        return mp

猜你喜欢

转载自blog.csdn.net/qq_38575545/article/details/86296591
今日推荐