【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/

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