For studying Scala, I wrote some code to solve the Equal problem on HackerRank. But I am stuck on test case #15 due to timeout.
Christy is interning at HackerRank. One day she has to distribute some chocolates to her colleagues. She is biased towards her friends and may have distributed the chocolates unequally. One of the program managers gets to know this and orders Christy to make sure everyone gets equal number of chocolates.
But to make things difficult for the intern, she is ordered to equalize the number of chocolates for every colleague in the following manner,
For every operation, she can choose one of her colleagues and can do one of the three things.
- She can give one chocolate to every colleague other than chosen one.
- She can give two chocolates to every colleague other than chosen one.
- She can give five chocolates to every colleague other than chosen one.
Calculate minimum number of such operations needed to ensure that every colleague has the same number of chocolates.
My code is like below I will appreciate your advice to improve performance.
object EqualsTest {
def main(args: Array[String]): Unit = {
val numOfTestCases = readInt();
Range(0, numOfTestCases).foreach(i => {
val numberCount = readInt();
var numbers = Array.ofDim[Int](numberCount)
val inputNumbers = scala.io.StdIn.readLine().split("""\s+""")
0.until(numberCount).foreach(i => {
numbers(i) = inputNumbers(i).trim.toInt
})
// val numbers = scala.io.StdIn.readLine().split(" ").map(s => s.toInt);
var baseLine = numbers.min
println(calOpCount(numbers, baseLine))
})
def f(b: Int)(s: Int): Int = {
val i = s - b
if (i==0) 0
else if (i == 1 || i == 2 || i == 5) 1
else (i/5 + (i%5)/2 + ((i%5)%2))
}
def calOpCount(source: Array[Int], baseLine: Int): Int = {
val baseLines = 0.to(baseLine)
val result = for {i <- baseLines; f1 = f(i)(_)} yield (source.map(s => f1(s.toInt)).sum)
result.min
}
}
}