Elixir Max Profit
defmodule MaxProfit do
def max_profit([first | _] = a) do
{_min_price, profit} =
Enum.reduce(a, {first, 0}, fn v, {min_price, profit} ->
min_price = min(min_price, v)
{min_price, max(profit, v - min_price)}
end)
profit
end
end
This tracks the lowest buy price seen so far and updates the best profit as it scans the prices once.