Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import java.util.*;
- class Solution {
- static int[] leastGreaterElement(int[] arr) {
- // write code here
- int n = arr.length;
- int [] ans = new int[n];
- Stack<Integer> st = new Stack<>();
- for(int i=n-1; i>=0; i--){
- while(st.size() > 0 && st.peek() <= arr[i]){
- st.pop();
- }
- if(st.size() == 0){
- ans[i] = -1;
- }
- else{
- ans[i] = st.peek();
- }
- st.push(arr[i]);
- }
- return ans;
- }
- }
- public class Main {
- public static void main(String[] args) throws Throwable {
- Scanner sc = new Scanner(System.in);
- int n = sc.nextInt();
- int arr[] = new int[n];
- for(int i=0;i<n;i++) {
- arr[i] = sc.nextInt();
- }
- int ans[] = Solution.leastGreaterElement(arr);
- for(int i=0;i<n;i++) {
- if(i == n-1) {
- System.out.print(ans[i] + "\n");
- }
- else {
- System.out.print(ans[i] + " ");
- }
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement