Python实现"买卖股票的最佳时机||"的一种方法

给定一个数组,数组中的元素表示股价,第几个元素就代表第几天的股价

设计算法来获得最大的利润,可以进行多次交易(买卖股票多次)

注意:同一时间内不能重复交易(卖股票之后必须先买股票)

Example 1:

Input: [7,1,5,3,6,4]
Output: 7
Explanation: Buy on day 2 (price = 1) and sell on day 3 (price = 5), profit = 5-1 = 4.
             Then buy on day 4 (price = 3) and sell on day 5 (price = 6), profit = 6-3 = 3.

Example 2:

Input: [1,2,3,4,5]
Output: 4
Explanation: Buy on day 1 (price = 1) and sell on day 5 (price = 5), profit = 5-1 = 4.
             Note that you cannot buy on day 1, buy on day 2 and sell them later, as you are
             engaging multiple transactions at the same time. You must sell before buying again.

Example 3:

Input: [7,6,4,3,1]
Output: 0
Explanation: In this case, no transaction is done, i.e. max profit = 0.

1:本题和"买卖股票的最佳时机"类似(https://mp.csdn.net/postedit/82467276),利用头指针pre、尾指针tail和maxProfit即可

def maxProfit(self, prices):
        """
        :type prices: List[int]
        :rtype: int
        """
        if len(prices)<=1:
            return 0
        pre = prices[0]    
        tail = prices[0]
        maxProfit = 0
        for i in prices[1:]:
            if i>=tail:     #对比当前元素和尾指针的大小
                tail=i    #替换尾指针为当前元素
            else:          #累加利润,然后头指针和尾指针从当前元素开始
                maxProfit += tail-pre
                pre = i
                tail = i
        maxProfit += tail-pre       #累加最后的利润
        return maxProfit

算法题来自:https://leetcode-cn.com/problems/best-time-to-buy-and-sell-stock-ii/description/

猜你喜欢

转载自blog.csdn.net/qiubingcsdn/article/details/82560881