O(n)时间求解最佳交易模型

Say you have an array for which the ith element is the price of a given stock on day i.

If you were only permitted to complete at most one transaction (ie, buy one and sell one share of the stock), design an algorithm to find the maximum profit.

给了一个由物品价格组成的时间序列如,(1,3,2,4)第一天价格为1,第二天价格为3,其他同理,求解如何买卖可以获利最大

要注意的是买的时间一定在卖的时间之前,于是该题就变成了当i<j时,最大的(aj-ai)值

第一想法是通过遍历元素,每个元素都与后面的元素进行比较,时间复杂度自然是O(n**2)

但是这道题可以采用另一种思路,设置最大收益benefit和已经找到的最小值mini,每个新来的元素与mini相减与benefit比较,同时元素与之前最小值mini比较,如此下来一次遍历便可以求解该问题

代码如下:

class Solution(object):
    def maxProfit(self, prices):
        """
        :type prices: List[int]
        :rtype: int
        """
        bene,mini=0,float('inf')
        for i in prices:
            mini=min(mini,i)
            bene=max(bene,i-mini)
        return bene

其中注意 mini设置为无穷大,bene设置为0

同时使用min和max函数避免使用if 精简代码

猜你喜欢

转载自blog.csdn.net/a5139515/article/details/78149021