【LeetCode】121. 买入和卖出股票的最佳时间

问题描述

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.

假设你有一个数组,其中的第i个元素是某只股票在第一天的价格。
如你最多只获准完成一项交易(即,买一股,卖一股),设计一个算法来寻找最大的利润。
注意,你不能在买股票之前卖掉它。

输入: [7,1,5,3,6,4]
输出: 5
说明: 在第二天(price = 1)买入,在第五天(price = 6)卖出,利润为5.
      不能在第一天(price = 7)卖出,在第二天(price = 1)买入,因为买入必须要在卖出前完成。

输入: [7,6,4,3,1]
输出: 0
说明: 在这个例子中,不进行任何交易,也就是说,最大利润为0.

Python 实现

这里需要注意的是,题目要求买入必须在卖出前实现,因此需要保证小值在前,大值在后,因此不能简单地找出最大值和最小值来解答这个问题。在遍历每个价格时,我们每次只进行一次更新操作,要么更新最小价格,要么在新的最小价格的基础上,再通过当前的价格来更新最大利润。

class Solution(object):
    def maxProfit(self, prices):
        """
        :type prices: List[int]
        :rtype: int
        """
        
        length = len(prices)
        if length < 2:
            return 0
        
        lowest_price = float('inf')
        profit = 0
        
        for price in prices:
            # Update if finding a lower price.
            if price < lowest_price:
                lowest_price = price
            # Update the profit if the current price is available to higher profit with the newest lowest_price.
            elif price - lowest_price > profit:
                profit = price - lowest_price
        return profit

链接:https://leetcode.com/problems/best-time-to-buy-and-sell-stock/

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章