For each day, return the number of days to wait for a warmer temperature.
[73,74,75,71,69,72,76,73] → [1,1,4,2,1,1,0,0]
# 4. Daily Temperatures
# Problem: For each day, return the number of days to wait for a warmer temperature.
# Input: [73,74,75,71,69,72,76,73], Output: [1,1,4,2,1,1,0,0]
# Time Complexity: O(n)
def daily_temperatures(temps)
result = Array.new(temps.size, 0)
stack = []
temps.each_with_index do |temp, today|
while !stack.empty? && temps[stack.last] < temp
prev_day = stack.pop
result[prev_day] = today - prev_day
puts "Found warmer day: #{prev_day} -> #{today} = #{result[prev_day]}"
end
stack.push(today)
end
result
O(n)
O(n)