LeetCode Best Time to Buy and Sell Stock III

LeetCode解题之Best Time to Buy and Sell Stock III


原题

给定每天的股票价格,如果最多允许两次交易,但手中最多只能持有一支股票,在再次买入的时候必须将之前的股票卖出,求能获取的最大利润。

注意点:

例子:

输入: prices = [2, 4, 6, 1, 3, 8, 3]

输出: 11([2,6]、[1,8]是两次进行买入卖出的时机)

解题思路

因为最多只能进行两次交易,所以可以将时间一划为二,分别找这两段时间内进行一次(也可能不进行交易)所能获得的最大利润(方法参见 Best Time to Buy and Sell Stock),将两者相加就是在这种划分情况下最多进行两次交易所能获取的最大利润。遍历所有的划分可能,就能找出最终的最大利润。如果每次都将时间段直接调用Best Time to Buy and Sell Stock的方法,复杂的用例会超时。我们可以先从前往后遍历,并缓存最多进行一次交易所能获取的最大利润;再从后往前遍历计算最多进行一次交易所能获取的最大利润,与对应的缓存相加就是在一次划分下的最大利润。

AC源码

class Solution(object):
    def maxProfit(self, prices):
        """
        :type prices: List[int]
        :rtype: int
        """
        total_max_profit = 0
        n = len(prices)
        first_profits = [0] * n
        min_price = float('inf')

        for i in range(n):
            min_price = min(min_price, prices[i])
            total_max_profit = max(total_max_profit, prices[i] - min_price)
            first_profits[i] = total_max_profit

        max_profit = 0
        max_price = float('-inf')
        for i in range(n - 1, 0, -1):
            max_price = max(max_price, prices[i])
            max_profit = max(max_profit, max_price - prices[i])
            total_max_profit = max(total_max_profit, max_profit + first_profits[i - 1])
        return total_max_profit


if __name__ == "__main__":
    assert Solution().maxProfit([2, 4, 6, 1, 3, 8, 3]) == 11
    assert Solution().maxProfit([1, 2]) == 1

欢迎查看我的Github (https://github.com/gavinfish/LeetCode-Python) 来获得相关源码。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值