// Print all elements in a list
fun printList(arr: List<Int>) {
println(arr.joinToString(" "))
}
// Calculate how many days you must wait for a warmer temperature
fun numberOfDaysToWait(temperatures: List<Int>): List<Int> {
val size = temperatures.size
val result = MutableList(size) { 0 }
val stack = ArrayDeque<Int>() // stack of indices
for (i in 0 until size) {
// While the current temperature is warmer than the temperature
// at the index stored at the top of the stack:
while (stack.isNotEmpty() && temperatures[i] > temperatures[stack.last()]) {
val idx = stack.removeLast()
result[idx] = i - idx
}
// Push the current index onto the stack
stack.addLast(i)
}
// Remaining indices in the stack have no warmer future day
// (result already contains zeros)
return result
}
fun main() {
val temperatures = listOf(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)
printList(result)
}
/*
run:
1 3 2 1 1 0 0 0
*/