121. Best Time to Buy and Sell Stock
easy
sliding-window
Find the maximum profit from a single buy/sell transaction.
Given array prices where prices[i] is the price on day i, find the maximum profit from one transaction.
Approach
Track the minimum price seen so far, and compute max profit at each step — O(n) time, O(1) space.
Solutions
Ruby
def max_profit(prices)
min_price = Float::INFINITY
max_profit = 0
prices.each do |price|
min_price = [min_price, price].min
max_profit = [max_profit, price - min_price].max
end
max_profit
end
Python
def max_profit(prices: list[int]) -> int:
min_price = float('inf')
max_profit = 0
for price in prices:
min_price = min(min_price, price)
max_profit = max(max_profit, price - min_price)
return max_profit
Go
func maxProfit(prices []int) int {
minPrice := math.MaxInt32
maxProfit := 0
for _, price := range prices {
if price < minPrice {
minPrice = price
}
profit := price - minPrice
if profit > maxProfit {
maxProfit = profit
}
}
return maxProfit
}
TypeScript
function maxProfit(prices: number[]): number {
let minPrice = Infinity;
let maxProfit = 0;
for (const price of prices) {
minPrice = Math.min(minPrice, price);
maxProfit = Math.max(maxProfit, price - minPrice);
}
return maxProfit;
}
Elixir
defmodule Solution do
def max_profit(prices) do
prices
|> Enum.reduce({Infinity, 0}, fn price, {min_price, max_profit} ->
new_min = min(min_price, price)
{new_min, max(max_profit, price - new_min)}
end)
|> elem(1)
end
end