mycode  70.94%

思路:其实没必要去考虑在计算了一个max-min后,后面又出现了一个新的的最小值的情况,因为res取值就是取自己和新的res的最大值

在遇见max值之前,遇见新的最小值,直接更新最小值

在遇见max值之后,遇见新的最小值,没关系啊,因为res已经记录了前面最大值和最小值之间的差啦,只要新的最小值之后能够找到新的最大值使得新的差值比res大,就去更新res,否则res不变啦

class Solution(object):
    def maxProfit(self, prices):
        """
        :type prices: List[int]
        :rtype: int
        """
        m = float('inf')
        n = 0
        pos1 = 0
        pos2 = 0
        res = 0
        for i in range(len(prices)):
            if prices[i] < m :
                pos1 = i
                m = prices[i]
            if prices[i] > m and i > pos1:
                res = max(res,prices[i]-m)
        return res
                
    

简化  77.91%

class Solution(object):
    def maxProfit(self, prices):
        """
        :type prices: List[int]
        :rtype: int
        """
        m = float('inf')
        res = 0
        for i in range(len(prices)):
            if prices[i] < m :
                m = prices[i]
            if prices[i] > m :
                res = max(res,prices[i]-m)
        return res

 

参考

class Solution(object):
    def maxProfit(self, prices):
        """
        :type prices: List[int]
        :rtype: int
        """
        if len(prices)<2:
            return 0
        lowest = prices[0]
        rst = 0
        for price in prices:
            if price<lowest:
                lowest = price
            rst = max(rst, price-lowest)
        return rst