天天看点

leetcode123. Best Time to Buy and Sell Stock III( 买卖股票的最佳时机 III)

题目要求

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

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

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

leetcode123. Best Time to Buy and Sell Stock III( 买卖股票的最佳时机 III)

补充 股票四连合集,看了不亏,没看后悔!!:

NO.1 leetcode 121 Best Time to Buy and Sell Stock(买卖股票的最佳时机)

NO.2 leetcode122. Best Time to Buy and Sell Stock II (买卖股票的最佳时机 II)

NO.3 leetcode123. Best Time to Buy and Sell Stock III( 买卖股票的最佳时机 III)

NO.4 leetcode188. Best Time to Buy and Sell Stock IV(买卖股票的最佳时机 IV)

解题思路

是第一道题的扩展,股票的最大盈利,但是限定了最多只能买卖两次,所以为了在限制条件中解题,我们设置四个变量

first_buy:在该天第一次买入股票可获得的最大收益

first_profit:在该天第一次卖出股票可获得的最大收益

second_buy: 在该天第二次买入股票可获得的最大收益

second_profit: 在该天第二次卖出股票可获得的最大收益

分别对四个变量进行相应的更新, 最后的secondprofit就是最后的收益。

实际上是找两段波峰波谷的问题。

主要代码python

class Solution(object):
    def maxProfit(self, prices):
        """
        :type prices: List[int]
        :rtype: int
        """
        first_buy = second_buy = float('inf')
        first_profit = second_profit = 0
        for i in range(len(prices)):
            # first_buy = min(first_buy, prices[i])
            # first_profit = max(first_profit, prices[i]-first_buy)
            # second_buy = min(second_buy, prices[i]-first_profit)
            # second_profit = max(second_profit, prices[i] - second_buy)
            if prices[i]<first_buy:
                first_buy = prices[i]
            if first_profit<prices[i] - first_buy:
                first_profit = prices[i] - first_buy
            # 第二次的当前买入价格要减去第一次的利润来求。
            if prices[i]-first_profit < second_buy:
                second_buy =  prices[i]-first_profit 
            if second_profit< prices[i] - second_buy:
                second_profit  = prices[i] - second_buy
        return second_profit
           

原题链接:https://leetcode-cn.com/problems/best-time-to-buy-and-sell-stock-iii

继续阅读