Skip to content

Instantly share code, notes, and snippets.

@olim7t
Last active December 29, 2015 02:39
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 olim7t/7602197 to your computer and use it in GitHub Desktop.
Save olim7t/7602197 to your computer and use it in GitHub Desktop.
// Naive solution (two passes)
def volume(l: List[Int]) = {
def peakRight(l: List[Int]) = l.foldRight(List(0)) { case (i, acc) => (i max acc.head) :: acc }.tail
def peakLeft(l: List[Int]) = peakRight(l.reverse).reverse
val waterLevels = peakLeft(l) zip peakRight(l) map { case (l, r) => l min r }
val volumes = l zip waterLevels map { case (g, w) => (w - g) max 0 }
volumes reduceLeft (_ + _)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment