Skip to content

Instantly share code, notes, and snippets.

@amoragon
Created October 14, 2013 07:53
Show Gist options
  • Save amoragon/6972265 to your computer and use it in GitHub Desktop.
Save amoragon/6972265 to your computer and use it in GitHub Desktop.
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)).
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment