739. Daily Temperatures

mono increasing/decreasing stack

Leetcode 496, 503, 739

class Solution {
    public int[] dailyTemperatures(int[] temperatures) {
        int[] result = new int[temperatures.length];
        // monoincreasing stack
        Stack<Integer> stack = new Stack<>();
        
        for(int i=temperatures.length-1; i>=0; i--){
            // use while not if!
            while (!stack.isEmpty() && temperatures[stack.peek()]<=temperatures[i]){
                stack.pop();
            }
            result[i] = stack.isEmpty() ? 0 : stack.peek() - i;
            stack.push(i);
        }
        return result;
    }
}

Last updated