Skip to content

Instantly share code, notes, and snippets.

@antarr
Created November 7, 2014 21:00
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save antarr/3824b0f990c1778e969b to your computer and use it in GitHub Desktop.
Save antarr/3824b0f990c1778e969b to your computer and use it in GitHub Desktop.
Write a program to determine the largest sum of contiguous integers in a list.
def largestSum(ns: List[Int]): Int ={
def sum(numbers: List[Int]) = numbers.foldLeft(0)((a,b) => a+ b)
@tailrec def loop(numbers: List[Int], large: Int): Int = numbers match{
case Nil => large
case _ => {
val thisSum = sum(numbers)
if(thisSum > large)
loop(numbers.tail, thisSum)
else
loop(numbers.tail,large)
}
}
(for{
i <- 1 to ns.length
window <- ns.sliding(i)
} yield loop(window.tail, sum(window))).max
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment