8.14 - hard - 40

188. Best Time to Buy and Sell Stock IV

看着知道是dp问题,但是找不出状态和转移方程
状态是dp[i][j] 针对前j各元素进行最多i次交易可以获得的最大利益。
dp[0][j] = 0 如果是0次交易则获得0
dp[i][0] = 0 如果针对第一个值prices[0],因为不能够交易,则获得利益为0

dp[i][j] = max(

  • dp[i][j-1] 不利用此次prices[j]所能获得的最大利益
  • for k in 0..j-1:
    dp[i-1][k-1] + price[j] - price[k] 利用此次prices[j],则prices[j]肯定是做为卖出点,且获得的利益是 针对 k-1进行i-1次交易所获得的最大值,加上这一次交易k为买入点,j为卖出点所获得的利益
    )
class Solution(object):
    def maxProfit(self, k, prices):
        """
        :type k: int
        :type prices: List[int]
        :rtype: int
        """
        # dp[i][j] 对前j个元素进行最多i次transactions获取的最大值
        if k <= 0:
            return 0
        if len(prices) <= 1:
            return 0
        res = 0
        if k >= len(prices)/2:
            base = prices[0]
            for p in prices[1:]:
                if p - base > 0:
                    res += p - base
                base = p
            return res
        
        dp = [[0 for _ in range(len(prices))] for _ in range(k+1)]
        for i in range(1, k+1):
            localmax = dp[i-1][0] - prices[0] 
            for j in range(1, len(prices)):
                dp[i][j] = max(dp[i][j-1],  prices[j] + localmax)
                localmax = max(localmax, dp[i-1][j-1] - prices[j])
        return dp[k][len(prices)-1]
                

你可能感兴趣的:(8.14 - hard - 40)