121. Best Time to Buy and Sell Stock

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 (i.e., buy one and sell one share of the stock), design an algorithm to find the maximum profit.

Note that you cannot sell a stock before you buy one.

最多只能买一只股票,使得收益最大。那就只需要维护一个从0到i当前股票最小值,然后和当前值做差得到当前最大收益,然后再和全局最大收益做max。

class Solution(object):
    def maxProfit(self, prices):
        """
        :type prices: List[int]
        :rtype: int
        """
        if len(prices) < 2:
            return 0
        ans = 0
        min_current = prices[0]
        for i in range(1, len(prices), 1):
            ans = max(ans, prices[i] - min_current)
            min_current = min(min_current, prices[i])
        return ans

 

你可能感兴趣的:(121. Best Time to Buy and Sell Stock)