fork download
  1. public class Main {
  2. /**
  3.   * Slightly modified code from
  4.   * https://w...content-available-to-author-only...s.org/next-greater-element/
  5.   * find a solution for the next element greater than current not less than N
  6.   */
  7.  
  8. static class stack {
  9. int top;
  10. int items[] = new int[100];
  11.  
  12. // Stack functions to be used by printNGE
  13. void push(int x)
  14. {
  15. if (top == 99)
  16. {
  17. System.out.println("Stack full");
  18. }
  19. else
  20. {
  21. items[++top] = x;
  22. }
  23. }
  24.  
  25. int pop()
  26. {
  27. if (top == -1)
  28. {
  29. System.out.println("Underflow error");
  30. return -1;
  31. }
  32. else
  33. {
  34. int element = items[top];
  35. top--;
  36. return element;
  37. }
  38. }
  39.  
  40. boolean isEmpty()
  41. {
  42. return (top == -1) ? true : false;
  43. }
  44. }
  45.  
  46. static void printNGE(int arr[], int n)
  47. {
  48. int i = 0;
  49. stack s = new stack();
  50. s.top = -1;
  51. int element, next;
  52.  
  53. /* push the first element to stack */
  54. s.push(arr[0]);
  55.  
  56. // iterate for rest of the elements
  57. for (i = 1; i < arr.length; i++)
  58. {
  59. next = arr[i];
  60.  
  61. if (s.isEmpty() == false)
  62. {
  63.  
  64. // if stack is not empty, then
  65. // pop an element from stack
  66. element = s.pop();
  67.  
  68. /* If the popped element is smaller than
  69.   next, then a) print the pair b) keep
  70.   popping while elements are smaller and
  71.   stack is not empty */
  72. while (n * element < next)
  73. {
  74. System.out.println(n + " * " + element + " --> " + next);
  75. if (s.isEmpty() == true)
  76. break;
  77. element = s.pop();
  78. }
  79.  
  80. /* If element is greater than next, then
  81.   push the element back */
  82. if (n * element > next)
  83. s.push(element);
  84. }
  85.  
  86. /* push next to stack so that we can find next
  87.   greater for it */
  88. s.push(next);
  89. }
  90.  
  91. /* After iterating over the loop, the remaining
  92.   elements in stack do not have the next greater
  93.   element, so print -1 for them */
  94. while (s.isEmpty() == false)
  95. {
  96. element = s.pop();
  97. next = -1;
  98. System.out.println(element + " -- " + next);
  99. }
  100. }
  101.  
  102. public static void main(String[] args)
  103. {
  104. int arr[] = { 2, 5, 4, 7, 3, 8, 9, 6 };
  105. int n = arr.length;
  106. printNGE(arr, 2);
  107. }
  108. }
Success #stdin #stdout 0.13s 36592KB
stdin
Standard input is empty
stdout
2 * 2 --> 5
2 * 3 --> 8
6 -- -1
9 -- -1
8 -- -1
7 -- -1
4 -- -1
5 -- -1