my-solutions/leetcode/0011-container-with-most-water/elixir/lib/solution.ex

28 lines
756 B
Elixir
Raw Normal View History

defmodule Solution do
@spec max_area(height :: [integer]) :: integer
def max_area(height) do
iter(0, height, 0, 0)
end
defp iter(prev, [head | tail], head_idx, max_vol) do
if prev >= head do
iter(prev, tail, head_idx + 1, max_vol)
else
max_vol = iter_inner(head, head_idx, tail, head_idx + 1, max_vol)
iter(head, tail, head_idx + 1, max_vol)
end
end
defp iter(_, [], _, max_vol), do: max_vol
defp iter_inner(a, a_idx, [head | tail], head_idx, max_vol) do
distance = head_idx - a_idx
min_height = min(a, head)
volume = min_height * distance
max_vol = max(max_vol, volume)
iter_inner(a, a_idx, tail, head_idx + 1, max_vol)
end
defp iter_inner(_, _, [], _, max_vol), do: max_vol
end