Daily Temperatures in Java: Explanation & Practice
Days until warmer temperature
Problem summary
Given an array of temperatures, return how many days you have to wait for a warmer temperature. Return 0 if no warmer day.
Starter code
public class Main {
public static void main(String[] args) {
int[] temps = {73, 74, 75, 71, 69, 72, 76, 73};
// Same as next greater element!
// Store indices, calculate distance
// Print: 1 1 4 2 1 1 0 0
}
}Expected output and test cases
- [73,74,75,71,69,72,76,73]
1 1 4 2 1 1 0 0
- [30,40,50,60]
1 1 1 0
- [30,20,10]
0 0 0
Hints
- Use monotonic decreasing stack storing indices
- When we find a warmer day, pop all cooler days
- Answer for popped index = current index - popped index
- Remaining in stack have no warmer day → answer is 0
Related Data Structures & Algorithms exercises
- Practice Valid Parentheses in Java
- Practice Next Greater Element in Java
- Practice Largest Rectangle in Histogram in Java
Practice all Data Structures & Algorithms exercises · Run this idea in the Java compiler