Erlang Stone Blocks
-module(stone_blocks).
-export([stone_blocks/1]).
stone_blocks(H) ->
{_, Blocks} = lists:foldl(fun(Hi, {Stack, BlocksCount}) ->
Stack1 = pop_while_greater(Stack, Hi),
case Stack1 of
[Hi | _] -> {Stack1, BlocksCount};
_ -> {[Hi | Stack1], BlocksCount + 1}
end
end, {[], 0}, H),
Blocks.
pop_while_greater([Top | Rest], Hi) when Top > Hi ->
pop_while_greater(Rest, Hi);
pop_while_greater(Stack, _Hi) ->
Stack.
This uses a stack of active heights and only counts a new block when the wall needs a new height segment.