Erlang Max Double Slice Sum
-module(max_double_slice_sum).
-export([max_double_slice_sum/1]).
max_double_slice_sum(A) ->
Size = length(A),
case Size < 3 of
true -> 0;
false ->
Arr = array:from_list(A),
P1 = build_p1(Arr, Size),
P2 = build_p2(Arr, Size),
lists:max([array:get(I, P1) + array:get(I, P2) || I <- lists:seq(1, Size - 2)])
end.
build_p1(Arr, Size) ->
P0 = array:set(1, 0, array:new(Size)),
lists:foldl(fun(I, Acc) ->
V = max(0, array:get(I - 1, Acc) + array:get(I - 1, Arr)),
array:set(I, V, Acc)
end, P0, lists:seq(2, Size - 2)).
build_p2(Arr, Size) ->
P0 = array:set(Size - 2, 0, array:new(Size)),
lists:foldl(fun(J, Acc) ->
V = max(0, array:get(J + 1, Acc) + array:get(J + 1, Arr)),
array:set(J, V, Acc)
end, P0, lists:seq(Size - 3, 1, -1)).
This keeps the best sum ending on the left and starting on the right, then combines them around each middle position.