https://leetcode.com/problems/daily-temperatures/
- Stack
- Monotonic Stack
Use a decreasing stack of indices. When a warmer day appears, resolve previous days.
O(n)
O(n)
import java.util.*;
class Solution {
public int[] dailyTemperatures(int[] temperatures) {
int n = temperatures.length;
int[] ans = new int[n];
Stack<Integer> stack = new Stack<>();
for (int i = 0; i < n; i++) {
while (!stack.isEmpty() && temperatures[i] > temperatures[stack.peek()]) {
int idx = stack.pop();
ans[idx] = i - idx;
}
stack.push(i);
}
return ans;
}
}