Skip to content

Instantly share code, notes, and snippets.

@mlhaufe
Created April 16, 2014 05:06
Show Gist options
  • Save mlhaufe/10809506 to your computer and use it in GitHub Desktop.
Save mlhaufe/10809506 to your computer and use it in GitHub Desktop.
Max Subsequence Sum
var xs = [-4,-3,-7,+2,+1,-1,-4], //[2,1] = 3
ys = [-2,11,-4,13,-5,-2], //[11,-4,13] = 20
zs = [5,15,-30,10,-5,40,10,-8] // [...] = 55
function sum(j,as){
var max = Math.max;
function tabulate(i,runMax,curMax){
if(i > j) return curMax
var newMax = max(runMax+as[i],as[i])
return tabulate(i + 1, newMax, max(curMax,newMax))
}
return j == 0 ? as[0] : tabulate(1,as[0],as[0])
}
sum(6,xs) //3
sum(5,ys) //20
sum(7,zs) //55
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment