LeetCode 121 Best Time to Buy and Sell Stock - Implementation

The approach

Track minimum price and maximum profit in a single pass.

function maxProfit(prices): minPrice = infinity maxProfit = 0 for price in prices: minPrice = min(minPrice, price) profit = price - minPrice maxProfit = max(maxProfit, profit) return maxProfit

O(n)O(n) time, O(1)O(1) space.