Created
August 19, 2015 05:55
-
-
Save feliperazeek/463a8aa85a0d65b032e3 to your computer and use it in GitHub Desktop.
Codility TapeEquilibrium (https://codility.com/demo/results/demo8HMGGH-TPP/)
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import scala.math.{min, abs} | |
object Solution { | |
def solution(A: Array[Int]): Int = { | |
if (A.size < 2 || A.size > 100000) sys.error(s"Invalid input - array size: ${A.size}") | |
val total = A.map(_.toLong).sum | |
(A.foldLeft[(Int, Long, Long)](-1, -1, 0l) { (t, i) => | |
if (i < -1000 || i > 1000) sys.error(s"Invalid array element: $i") | |
val (x, currentMin, lastLeftSum) = t | |
val index = x + 1 | |
(index + 1 == A.size) match { | |
case true => | |
// Do nothing on the last element | |
t | |
case false => | |
val leftSum = lastLeftSum.toLong + A(index).toLong | |
val rightSum = total - leftSum | |
val thisMin = abs(leftSum- rightSum) | |
val results = if (currentMin == -1) thisMin | |
else min(currentMin, thisMin) | |
(index, results, leftSum) | |
} | |
})._2.toInt | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment