Advertisement
korobushk

stacknextgreatelement

Apr 17th, 2021
1,056
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 0.97 KB | None | 0 0
  1. package nextgreaterelement;
  2.  
  3. import java.util.Arrays;
  4. import java.util.Stack;
  5.  
  6. public class app {
  7.     public static void main(String[] args) {
  8.         int arr[] = {1, 2, 4, 8, 6, 10};
  9.        
  10.        
  11.        
  12.         System.out.println(Arrays.toString(nextGreater(arr)));
  13.     }
  14.  
  15.     static int[] nextGreater(int arr[]) {
  16.         Stack<Integer> stack = new Stack<>();
  17.  
  18.         stack.push(arr[arr.length-1]);
  19.  
  20.         int a[] = new int[arr.length];
  21.      
  22.        
  23.         a[arr.length-1] = -1;
  24.  
  25.         for (int i = arr.length-2; i >= 0; i--) {
  26.             while (!stack.isEmpty() &&              
  27.                     stack.peek() <= arr[i]) {
  28.  
  29.                 stack.pop();                        
  30.             }
  31.  
  32.             if (stack.isEmpty())
  33.                 a[i] = -1;                          
  34.             else
  35.                 a[i] = stack.peek();
  36.  
  37.             stack.push(arr[i]);
  38.         }
  39.  
  40.         return a;
  41.     }
  42. }
  43.  
  44. //Output:
  45. //        2 4 8 10 10 -1
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement