File tree Expand file tree Collapse file tree 1 file changed +33
-0
lines changed Expand file tree Collapse file tree 1 file changed +33
-0
lines changed Original file line number Diff line number Diff line change 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+ }
You can’t perform that action at this time.
0 commit comments