-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathNGE.java
More file actions
66 lines (60 loc) · 1.78 KB
/
Copy pathNGE.java
File metadata and controls
66 lines (60 loc) · 1.78 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
54
55
56
57
58
59
60
61
62
63
64
65
66
package Array;
import java.util.Stack;
/**
* use flag, stack queue, continue, tmp variable, use for loop first thing
* Created by Prashant on 6/12/16.
* http://www.geeksforgeeks.org/next-greater-element/
*/
public class NGE {
static void printNGE(int a[], int n)
{
Stack<Integer> s = new Stack<Integer>();
System.out.println("for: " + a[n-1] + ": " + -1);
s.push(a[n-1]);
for(int i = n-2; i >= 0; ) {
if(!s.isEmpty()) {
System.out.println("stack peek: " + s.peek());
if(s.peek() > a[i]) {
System.out.println("for: " + a[i] + ": " + s.peek());
s.push(a[i--]);
} else {
s.pop();
continue;
}
} else {
System.out.println("for: " + a[i] + ": " + -1);
s.push(a[i--]);
}
}
}
public static void nge(int[] a) {
Stack<Integer> s = new Stack<Integer>();
int i = a.length-1;
System.out.println("NGE for:" + a[i] + "-->" + -1);
s.push(a[i--]);
while(i>=0) {
if(s.isEmpty()==false) {
if(s.peek()>a[i]) {
System.out.println("NGE for:" + a[i] + "-->" + s.peek());
s.push(a[i--]);
} else {
s.pop();
continue;
}
} else {
System.out.println("NGE for:" + a[i] + "-->" + -1);
s.push(a[i--]);
}
}
System.out.println();
}
public static void main(String[] args) {
int[] a= {4, 5, 2, 25};
nge(a);
int [] b = {13, 7, 6, 12};
nge(b);
int arr[]= {11, 13, 21, 3};
nge(arr);
System.out.print(" ");
}
}