DEV Community

Prashant Mishra
Prashant Mishra

Posted on

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;
    }
}
Enter fullscreen mode Exit fullscreen mode

Top comments (0)

👋 Kindness is contagious

Explore a trove of insights in this engaging article, celebrated within our welcoming DEV Community. Developers from every background are invited to join and enhance our shared wisdom.

A genuine "thank you" can truly uplift someone’s day. Feel free to express your gratitude in the comments below!

On DEV, our collective exchange of knowledge lightens the road ahead and strengthens our community bonds. Found something valuable here? A small thank you to the author can make a big difference.

Okay