Created
May 16, 2016 08:49
-
-
Save ylegall/70360532ef5a0339047c371ab48c9d71 to your computer and use it in GitHub Desktop.
find the largest product of 3 integers in an array
This file contains hidden or 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
object LargestProductOf3 | |
{ | |
def largestProductOf3(a: Array[Int]): Int = { | |
var (max, max2, max3) = (a(0), a(0), a(0)) | |
var (min, min2) = (a(0), a(0)) | |
a.foreach(i => { | |
if (i >= max) { | |
max3 = max2 | |
max2 = max | |
max = i | |
} else if (i >= max2) { | |
max3 = max2 | |
max2 = i | |
} else if (i > max3) { | |
max3 = i | |
} else if (i <= min) { | |
min2 = min | |
min = i | |
} else if (i < min2) { | |
min2 = i | |
} | |
}) | |
return math.max(max * max2 * max3, min * min2 * max) | |
} | |
def largestProductOf3Naive(array: Array[Int]): Int = { | |
var max = array(0) | |
(0 until array.length - 2).foreach(i => { | |
(i + 1 until array.length - 1).foreach(j => { | |
(j + 1 until array.length).foreach(k => { | |
max = math.max(max, array(i) * array(j) * array(k)) | |
}) | |
}) | |
}) | |
return max | |
} | |
def main(args: Array[String]): Unit = { | |
val rand = scala.util.Random | |
val array = new Array[Int](1000).map(_ => -1000 + rand.nextInt(2001)) | |
var elapsed = System.nanoTime() | |
val fastResult = largestProductOf3(array) | |
elapsed = (System.nanoTime() - elapsed) | |
println(s"fast result $fastResult in ${elapsed / 1000000.0} ms") | |
elapsed = System.nanoTime() | |
val slowResult = largestProductOf3Naive(array) | |
elapsed = (System.nanoTime() - elapsed) | |
println(s"slow result $slowResult in ${elapsed / 1000000.0} ms") | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment