Skip to content

Instantly share code, notes, and snippets.

@anil477
Last active May 28, 2017 14:07
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save anil477/0ed820f926d183b41c5b6f00f5af4bd0 to your computer and use it in GitHub Desktop.
Save anil477/0ed820f926d183b41c5b6f00f5af4bd0 to your computer and use it in GitHub Desktop.
Next greater element in an array
// 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