object WarmerDays {
// Print all elements in a sequence
def printSeq(arr: Seq[Int]): Unit = {
println(arr.mkString(" "))
}
// Calculate how many days you must wait for a warmer temperature
def numberOfDaysToWait(temperatures: Seq[Int]): Seq[Int] = {
val size = temperatures.length
val result = Array.fill(size)(0)
val stack = scala.collection.mutable.Stack[Int]() // stack of indices
for (i <- 0 until size) {
// While the current temperature is warmer than the temperature
// at the index stored at the top of the stack:
while (stack.nonEmpty && temperatures(i) > temperatures(stack.top)) {
val idx = stack.pop()
result(idx) = i - idx
}
// Push the current index onto the stack
stack.push(i)
}
// Remaining indices in the stack have no warmer future day
// (result already contains zeros)
result.toSeq
}
def main(args: Array[String]): Unit = {
val temperatures = Seq(82, 84, 81, 58, 85, 89, 75, 71)
// 82 -> 84 = 1
// 84 -> 81 -> 58 -> 85 = 3
// 81 -> 58 -> 85 = 2
// 58 -> 85 = 1
// 85 -> 89 = 1
// 89 -> 75 -> 71 = 0
// 75 -> 71 = 0
val result = numberOfDaysToWait(temperatures)
printSeq(result)
}
}
/*
run:
1 3 2 1 1 0 0 0
*/