|
7 | 7 | import java.util.Arrays;
|
8 | 8 | import java.util.Stack;
|
9 | 9 |
|
10 |
| -public class MonotonicIncreasingStack |
11 |
| -{ |
| 10 | +public class MonotonicIncreasingStack { |
12 | 11 |
|
13 |
| - public static int[] nextGreaterElement(int[] arr) |
14 |
| - { |
| 12 | + private MonotonicIncreasingStack() { |
| 13 | + throw new AssertionError("Cannot instantiate utility class"); |
| 14 | + } |
| 15 | + |
| 16 | + public static int[] nextGreaterElement(int[] arr) { |
15 | 17 | int n = arr.length;
|
16 | 18 | int[] result = new int[n];
|
17 | 19 | Stack<Integer> stack = new Stack<>();
|
18 | 20 |
|
19 |
| - for (int i = n - 1; i >= 0; i--) |
20 |
| - { |
21 |
| - while (!stack.isEmpty() && arr[i] >= arr[stack.peek()]) |
22 |
| - { |
| 21 | + for (int i = n - 1; i >= 0; i--) { |
| 22 | + while (!stack.isEmpty() && arr[i] >= arr[stack.peek()]) { |
23 | 23 | stack.pop();
|
24 | 24 | }
|
25 |
| - |
26 | 25 | result[i] = stack.isEmpty() ? -1 : arr[stack.peek()];
|
27 | 26 | stack.push(i);
|
28 | 27 | }
|
29 |
| - |
30 | 28 | return result;
|
31 | 29 | }
|
32 | 30 |
|
33 |
| - public static int[] nextSmallerElement(int[] arr) |
34 |
| - { |
| 31 | + public static int[] nextSmallerElement(int[] arr) { |
35 | 32 | int n = arr.length;
|
36 | 33 | int[] result = new int[n];
|
37 | 34 | Stack<Integer> stack = new Stack<>();
|
38 | 35 |
|
39 |
| - for (int i = n - 1; i >= 0; i--) |
40 |
| - { |
41 |
| - while (!stack.isEmpty() && arr[i] <= arr[stack.peek()]) |
42 |
| - { |
| 36 | + for (int i = n - 1; i >= 0; i--) { |
| 37 | + while (!stack.isEmpty() && arr[i] <= arr[stack.peek()]) { |
43 | 38 | stack.pop();
|
44 | 39 | }
|
45 |
| - |
46 | 40 | result[i] = stack.isEmpty() ? -1 : arr[stack.peek()];
|
47 | 41 | stack.push(i);
|
48 | 42 | }
|
49 |
| - |
50 | 43 | return result;
|
51 | 44 | }
|
52 | 45 |
|
53 |
| - public static void main(String[] args) |
54 |
| - { |
| 46 | + public static void main(String[] args) { |
55 | 47 | int[] arr = {4, 5, 2, 10, 8};
|
56 | 48 |
|
57 | 49 | int[] nextGreater = nextGreaterElement(arr);
|
|
0 commit comments