121. Best Time to Buy and Sell Stock

Traverse list, 不断检查是不是有新的更好的deal,定义为,更低的买入价,以及刷新后的卖出价,而且sell_price-lowest_price>原来的max_profit.

class Solution:
    def maxProfit(self, prices: List[int]) -> int:
        # This is time serial data
        # Note that this is not an online problem.
        # We can refresh our answers when we traverse the list
        if not prices: 
            return 0
        max_profit = 0
        lowest_price = prices[0]  # init to be the first day price
        sell_price = 0
        for i in range(1,len(prices)):
            if prices[i] < lowest_price:
                lowest_price = prices[i]   # a new buy, but max_profit is not updated yet
                sell_price = 0
            elif prices[i] > max(sell_price, lowest_price):
                sell_price = prices[i]
                max_profit = max(sell_price - lowest_price, max_profit)  # a new sell
        return max_profit
                

看了Leetcode的solution。一个是for loop可以直接用 element in,另外就是sell_price其实没有必要定义,完全是浪费的。

class Solution:
    def maxProfit(self, prices: List[int]) -> int:
        # This is time serial data
        # Note that this is not an online problem.
        # We can refresh our answers when we traverse the list
        if not prices: 
            return 0
        max_profit = 0
        lowest_price = prices[0]  # init to be the first day price
        for price in prices:
            if price < lowest_price:
                lowest_price = price   # a new buy, but max_profit is not updated yet
            elif price > lowest_price:
                max_profit = max(price - lowest_price, max_profit)  # a new sell
        return max_profit
上一篇:LeetCode_121_买卖股票的最佳时机


下一篇:053试题 121 - autotask background process