Elixir Max Counters
defmodule MaxCounters do
def max_counters(n, a) do
condition = n + 1
{counters, _max_counter, last_update} =
Enum.reduce(a, {%{}, 0, 0}, fn v, {counters, max_counter, last_update} ->
cond do
v <= n ->
index = v - 1
updated = max(Map.get(counters, index, 0), last_update) + 1
{Map.put(counters, index, updated), max(max_counter, updated), last_update}
v == condition ->
{counters, max_counter, max_counter}
true ->
{counters, max_counter, last_update}
end
end)
0..(n - 1)
|> Enum.map(fn i -> max(Map.get(counters, i, 0), last_update) end)
end
end
This delays the expensive “set all counters to max” work until it is really needed, which keeps the solution fast.