Skip to content

Instantly share code, notes, and snippets.

@amoragon
amoragon / mcs.erl
Created October 14, 2013 07:53
Max consecutive sum - Find the maximum sum possible from picking a contiguous subsequence of an array. [-1, 5, 6, -2, 20, -50, 4] What is the largest sum of contiguous elements available in this list? In the example above, the maximum sum would be 29: [-1, 5, 6, -2, 20, -50, 4], because (5 + 6 - 2 + 20 = 29). End one element later and you'll go …
-module (mcs).
-export([max/1]).
max(Nums) ->
find_max(Nums, 0, 0).
find_max([], _MaxEndingHere, MaxSoFar) -> MaxSoFar;
find_max([First | Tail], MaxEndingHere, MaxSoFar) ->
find_max(Tail, max(0, MaxEndingHere + First), max(MaxSoFar, MaxEndingHere)).