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 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. downward sloping line profit = 0
class Solution(object): def maxProfit(self, prices): """ :type prices: List[int] :rtype: int """ buy, profit = prices 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