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
复制代码

 

posted @   whatyouthink  阅读(98)  评论(0编辑  收藏  举报
努力加载评论中...
点击右上角即可分享
微信分享提示