fork download
  1. import java.util.*;
  2. import java.lang.*;
  3. import java.io.*;
  4. class Ideone{
  5. public static void main (String[] args) throws java.lang.Exception{
  6. int[] arr = {6,3,1,8,2,9,7};
  7. Stack<Integer> st1 = new Stack<Integer>();
  8. Stack<Integer> st2 = new Stack<Integer>();
  9. List<Integer> result = new ArrayList<>();
  10.  
  11. for(int i=arr.length-1;i>=0;--i){
  12. while(!st1.isEmpty() && arr[(int)st1.peek()] < arr[i]){
  13. st2.push(st1.pop());
  14. }
  15.  
  16. if(st2.isEmpty()) result.add(-1);
  17. else result.add(arr[(int)st2.peek()]);
  18.  
  19. while(!st2.isEmpty()) st1.push(st2.pop());
  20.  
  21. if(st1.isEmpty() || arr[(int)st1.peek()] > arr[i]){
  22. st1.push(i);
  23. }
  24. }
  25.  
  26. Collections.reverse(result);
  27. System.out.println(Arrays.toString(arr));
  28. System.out.println(result.toString());
  29. }
  30. }
Success #stdin #stdout 0.09s 47100KB
stdin
Standard input is empty
stdout
[6, 3, 1, 8, 2, 9, 7]
[2, 2, -1, 7, -1, 7, -1]