Advertisement
unknown_0711

Untitled

Dec 19th, 2022
29
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 0.99 KB | None | 0 0
  1. import java.util.*;
  2.  
  3. class Solution {
  4. static int[] leastGreaterElement(int[] arr) {
  5. // write code here
  6. int n = arr.length;
  7. int [] ans = new int[n];
  8. Stack<Integer> st = new Stack<>();
  9. for(int i=n-1; i>=0; i--){
  10. while(st.size() > 0 && st.peek() <= arr[i]){
  11. st.pop();
  12. }
  13. if(st.size() == 0){
  14. ans[i] = -1;
  15. }
  16. else{
  17. ans[i] = st.peek();
  18. }
  19. st.push(arr[i]);
  20. }
  21. return ans;
  22. }
  23. }
  24.  
  25.  
  26. public class Main {
  27. public static void main(String[] args) throws Throwable {
  28. Scanner sc = new Scanner(System.in);
  29.  
  30. int n = sc.nextInt();
  31. int arr[] = new int[n];
  32. for(int i=0;i<n;i++) {
  33. arr[i] = sc.nextInt();
  34. }
  35. int ans[] = Solution.leastGreaterElement(arr);
  36. for(int i=0;i<n;i++) {
  37. if(i == n-1) {
  38. System.out.print(ans[i] + "\n");
  39. }
  40. else {
  41. System.out.print(ans[i] + " ");
  42. }
  43. }
  44. }
  45. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement