Daily Temperatures

Problem Same as : Next greater element than the stack top class Solution { public int[] dailyTemperatures(int[] temperatures) { int result[] = new int[temperatures.length]; Stack stack = new Stack(); for(int i=0;i= temperatures[i]){ stack.push(new Pair(temperatures[i],i)); } else{ while(!stack.isEmpty() && stack.peek().t

Mar 22, 2025 - 14:07
 0
Daily Temperatures

Problem
Same as : Next greater element than the stack top

class Solution {
    public int[] dailyTemperatures(int[] temperatures) {
        int result[] = new int[temperatures.length];
        Stack<Pair> stack = new Stack<>();

        for(int  i=0;i< temperatures.length;i++){
            if(stack.isEmpty() || stack.peek().t >= temperatures[i]){
                stack.push(new Pair(temperatures[i],i));
            }
            else{
                while(!stack.isEmpty() && stack.peek().t < temperatures[i]){
                    result[stack.peek().i] = i-stack.peek().i;
                    stack.pop();
                }
                stack.push(new Pair(temperatures[i],i));
            }
        }
        return result;
    }
}
class Pair{
    int t;
    int i;
    public Pair(int t, int i){
        this.t = t;
        this.i = i;
    }
}