Leetcode 188 Python

本文介绍了一种基于动态规划思想的算法,用于计算在限制交易次数的情况下,如何通过买卖股票获得最大利润。该算法适用于一系列股票价格数据,通过定义全局和局部收益来实现最优策略。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

解题思路:使用动态规划的思想。定义全局收益glob和局部收益local,局部收益即当天已经全部卖出可获得的最大收益。
动态转移方程如下:
diff = prices[i] - prices[i-1]
local[i][j] = max(local[i-1][j]+diff,glob[i-1][j-1]+max(0,diff))
此处分两种情况,i-1天时卖了股票和i-1前已经全部卖出。
glob[i][j] = max(local[i][j],glob[i-1][j])

class Solution(object):
    def maxProfit(self, k, prices):
        """
        :type k: int
        :type prices: List[int]
        :rtype: int
        """
        profit = []
        i = 0
        while(i<len(prices)):
            j = i+1
            if j == len(prices):
                break
            if prices[j] > prices[i]:
                while j < len(prices)-1 and prices[j+1]>prices[j]:
                    j += 1
                profit.append(prices[j]-prices[i])
                i = j
            i += 1
        ans = 0
        if len(profit) <= k:
            for p in profit:
                ans += p
        else:
            local = [[0 for i in range(k+1)] for j in range(len(prices))]
            glob = [[0 for i in range(k+1)] for j in range(len(prices))]
            for i in range(1,len(prices)):
                for j in range(1,k+1):
                    diff = prices[i] - prices[i - 1]
                    local[i][j] = max(glob[i - 1][j - 1] + max(0,diff), local[i - 1][j] + diff)
                    glob[i][j] = max(glob[i-1][j],local[i][j])

            ans = glob[len(prices)-1][k]
        return ans
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值