Python solution with detailed explanation


  • 0
    G

    Solution

    Best Time to Buy and Sell Stock https://leetcode.com/problems/best-time-to-buy-and-sell-stock/

    • There is a linear time constant space solution to this problem.
    • Start by initializing buy price as prices[0] and profit as 0.
    • Now iterate through the prices array. Update profit for every value. If we find that the current value is lesser than the buy value, update the buy value.
    • There are 2 interesting test cases: upward sloping line indicating profit = price[N-1]-price[0]. downward sloping line profit = 0
    class Solution(object):
        def maxProfit(self, prices):
            """
            :type prices: List[int]
            :rtype: int
            """
            buy, profit = prices[0] if len(prices) else -1, 0
            for i in range(1, len(prices)):
                profit = max(profit, prices[i]-buy)
                buy = min(buy, prices[i])
            return profit
    

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.