-
Notifications
You must be signed in to change notification settings - Fork 1k
/
Next_Greater_Element.java
75 lines (64 loc) · 1.77 KB
/
Next_Greater_Element.java
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
67
68
69
70
71
72
73
74
75
/*
- Next Greater Element :
given an array, we have to find the next greater element for every element in that array
ALGORITHM:
* Initialize stack and array
* If the stack is empty then -1 is printed(no greater element to the right)
* If not, then if the topmost element is greater than the number, print it
* If topmost element is less then pop stack until empty or greater number is found
*/
import java.util.Scanner;
import java.lang.Stack;
public class NextGreaterElement {
//next_greater_element method
public static void next_greater_element(int[] array, int n)
{
Stack<Integer> st=new Stack<>();
int v[]=new int[n];
for(int i=n-1;i>=0;i--)
{
if(st.empty())
v[i]=-1;
else if(st.empty()!=true && st.top()>array[i])
v[i]=st.top();
else if(st.empty()!=true && st.top()<=array[i])
{
while(st.empty()!=true && st.top()<=array[i])
st.pop();
if(st.empty())
v[i]=-1;
else
v[i]=st.top();
}
st.push(array[i]);
}
for(int i=0;i<n;i++)
System.out.print(v[i]+" ");
}
//main method
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.print("Enter the number of elements: ");
//Input the number of elements you want in the array
int n = sc.nextInt();
//Creating array of n elements
int[] array = new int[n];
System.out.print("Enter the elements : ");
//Putting elements in the array
for(int i = 0 ; i < n ; i++) {
array[i] = sc.nextInt();
}
//Calling next_greater_element method
NextGreaterElement.next_greater_element(array, n);
}
}
}
/*
- Test Cases :
Input : Enter the number of elements: 5
Enter the elements : 12 34 54 2 62
Output : 34 54 62 62 -1
- Complexity Analysis :
* Time Complexity : O(n)
* Space Complexity : O(n)
*/