Last active
May 28, 2017 14:07
-
-
Save anil477/0ed820f926d183b41c5b6f00f5af4bd0 to your computer and use it in GitHub Desktop.
Next greater element in an array
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// The idea is to insert the newly arrived element in the sorted manner and | |
// pop all element that is smaller then the newly arrived element. | |
// https://www.youtube.com/watch?v=8P-Z7Oc8x9I | |
// don't use stack.peek() == null for checking is the stack is empty. It will throw and error. use stack.isEmpty() | |
import java.util.*; | |
class great{ | |
public static void main(String args[]) { | |
int[] a = new int[]{11, 13, 21, 3, 23}; | |
Stack<Integer> s = new Stack<Integer>(); | |
s.push(a[0]); | |
for (int i = 1; i < a.length; i++) { | |
if (s.peek() != null) { | |
while (true) { | |
if (s.isEmpty() || s.peek() > a[i]) { | |
break; | |
} | |
System.out.println(s.pop() + ":" + a[i]); | |
} | |
} | |
s.push(a[i]); | |
} | |
while (!s.isEmpty()) { | |
System.out.println(s.pop() + ":" + -1); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment