Advertisement
exmkg

Untitled

Sep 28th, 2024
89
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.08 KB | None | 0 0
  1. class Solution {
  2.     public int[] dailyTemperatures(int[] temperatures) {
  3.         int n = temperatures.length;
  4.  
  5.         // Initially, all 0, stores distance between their next greater element
  6.         // and the current temperature.
  7.         int[] nge = new int[n];
  8.  
  9.         Stack<Integer> st = new Stack<>();
  10.         // Move from right to left.
  11.         for (int i = n - 1; i >= 0; i--) {
  12.             // Pop until we find the next greater element to the right
  13.             // (until temperatures[st.top()] > temperatures[i]).
  14.             while (!st.isEmpty() && temperatures[st.peek()] <= temperatures[i]) {
  15.                 st.pop();
  16.             }
  17.  
  18.             // If the stack is not empty, then we have some next greater element,
  19.             // so we take the distance between the next greater and the current temperature.
  20.             if (!st.isEmpty()) {
  21.                 nge[i] = st.peek() - i; // The distance between next greater and current.
  22.             }
  23.  
  24.             // Push the index of the current temperature in the stack.
  25.             st.push(i);
  26.         }
  27.        
  28.         return nge;
  29.     }
  30. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement