Skip to content

Commit b373360

Browse files
authored
Create Next Greater Element.java
1 parent 27f9715 commit b373360

File tree

1 file changed

+33
-0
lines changed

1 file changed

+33
-0
lines changed
Lines changed: 33 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,33 @@
1+
//Problem Statement : https://practice.geeksforgeeks.org/problems/next-larger-element-1587115620/1?utm_source=gfg&utm_medium=article&utm_campaign=bottom_sticky_on_article
2+
3+
class Solution
4+
{
5+
//Function to find the next greater element for each element of the array.
6+
public static long[] nextLargerElement(long[] arr, int n)
7+
{
8+
// Your code here
9+
//Lets play with Stack::
10+
//Brute Force :::
11+
long[] res = new long[n];
12+
int k=n-1;
13+
Stack<Long> st = new Stack();
14+
for(int i=n-1;i>=0;i--){
15+
if(st.isEmpty()){
16+
res[i] =-1;
17+
}else if(st.peek()>arr[i]){
18+
res[i] =st.peek();
19+
}else{
20+
while(!st.isEmpty() && st.peek()<=arr[i]){
21+
st.pop();
22+
}
23+
if(st.isEmpty()){
24+
res[i] =-1;
25+
}else{
26+
res[i] =st.peek();
27+
}
28+
}
29+
st.push(arr[i]);
30+
}
31+
return res;
32+
}
33+
}

0 commit comments

Comments
 (0)