Faaez Razeen

Best Time to Buy and Sell Stock

  • 2 min read
  • LC-Easy
  • Sliding Window

3 years ago

Solution

TimeSpaceExplanation
O(n)O(1)
def maxProfit(self, prices: List[int]) -> int: l, r = 0, 1 max_profit = 0 for r in range(len(prices)): if prices[l] < prices[r]: profit = prices[r] - prices[l] max_profit = max(max_profit, profit) else: l = r return max_profit

Alternate solution that I solved on July 23rd, 2024 after not Leetcoding for a month

def maxProfit(self, prices: List[int]) -> int: l, r = 0, 1 max_profit = 0 for r in range(len(prices)): max_profit = max(max_profit, prices[r] - prices[l]) if prices[r] < prices[l]: l = r return max_profit