-
Notifications
You must be signed in to change notification settings - Fork 27
Expand file tree
/
Copy pathHelp_Classmates.java
More file actions
53 lines (47 loc) · 1.08 KB
/
Help_Classmates.java
File metadata and controls
53 lines (47 loc) · 1.08 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
import java.util.*;
import java.io.*;
class GFG {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int t = sc.nextInt();
while (t > 0) {
int n = sc.nextInt();
int array[] = new int[n];
for (int i = 0; i < n; ++i) {
array[i] = sc.nextInt();
}
Solution ob = new Solution();
int ans[] = ob.help_classmate(array, n);
for (int i = 0; i < n; i++)
System.out.print(ans[i] + " ");
System.out.println();
t--;
}
}
}
class Solution {
public static int[] help_classmate(int arr[], int n) {
int[] ans = new int[n];
// O(n)
Arrays.fill(ans, -1);
Stack<Integer> st = new Stack<>();
for (int i = 0; i < n; i++) {
while (!st.isEmpty() && arr[st.peek()] > arr[i]) {
ans[st.pop()] = arr[i];
}
st.push(i);
}
return ans;
// O(n2)
// for(int i = 0; i<n; i++){
// int curr = arr[i];
// for(int j = i+1; j<n; j++){
// if( arr[j] < curr ){
// ans[i] = arr[j];
// break;
// }
// }
// }
// return ans;
}
}