Skip to content

Commit 3d026b5

Browse files
authored
Fix comments and formatting in MonotonicIncreasingStack
1 parent 1debee0 commit 3d026b5

File tree

1 file changed

+26
-24
lines changed

1 file changed

+26
-24
lines changed
Lines changed: 26 additions & 24 deletions
Original file line numberDiff line numberDiff line change
@@ -1,44 +1,45 @@
1-
/*Contributor: Nayan Saraff
1+
/* Contributor: Nayan Saraff
2+
*
3+
* This Monotonic Increasing Stack is a popular algorithm which helps
4+
* in solving various problems including Stock Span, Trapping Rain Water
5+
*/
26

3-
This Monotonic Increasing Stack is a popular algorithm which helps
4-
in solving various problems including the Stock Span, Trapping Rain water*/
7+
import java.util.Arrays;
8+
import java.util.Stack;
59

10+
public class MonotonicIncreasingStack
11+
{
612

7-
import java.util.*;
8-
9-
public class MonotonicIncreasingStack {
10-
11-
// Returns Next Greater Element for each element in the array
12-
public static int[] nextGreaterElement(int[] arr) {
13+
public static int[] nextGreaterElement(int[] arr)
14+
{
1315
int n = arr.length;
1416
int[] result = new int[n];
15-
Stack<Integer> stack = new Stack<>(); // stores indices
17+
Stack<Integer> stack = new Stack<>();
1618

17-
for (int i = n - 1; i >= 0; i--) {
18-
// Pop elements smaller or equal to arr[i]
19-
while (!stack.isEmpty() && arr[i] >= arr[stack.peek()]) {
19+
for (int i = n - 1; i >= 0; i--)
20+
{
21+
while (!stack.isEmpty() && arr[i] >= arr[stack.peek()])
22+
{
2023
stack.pop();
2124
}
2225

23-
// If stack is empty, no greater element to the right
2426
result[i] = stack.isEmpty() ? -1 : arr[stack.peek()];
25-
26-
// Push current index onto stack
2727
stack.push(i);
2828
}
2929

3030
return result;
3131
}
3232

33-
// Returns Next Smaller Element for each element in the array
34-
public static int[] nextSmallerElement(int[] arr) {
33+
public static int[] nextSmallerElement(int[] arr)
34+
{
3535
int n = arr.length;
3636
int[] result = new int[n];
37-
Stack<Integer> stack = new Stack<>(); // stores indices
37+
Stack<Integer> stack = new Stack<>();
3838

39-
for (int i = n - 1; i >= 0; i--) {
40-
// Pop elements greater or equal to arr[i]
41-
while (!stack.isEmpty() && arr[i] <= arr[stack.peek()]) {
39+
for (int i = n - 1; i >= 0; i--)
40+
{
41+
while (!stack.isEmpty() && arr[i] <= arr[stack.peek()])
42+
{
4243
stack.pop();
4344
}
4445

@@ -49,7 +50,8 @@ public static int[] nextSmallerElement(int[] arr) {
4950
return result;
5051
}
5152

52-
public static void main(String[] args) {
53+
public static void main(String[] args)
54+
{
5355
int[] arr = {4, 5, 2, 10, 8};
5456

5557
int[] nextGreater = nextGreaterElement(arr);
@@ -60,4 +62,4 @@ public static void main(String[] args) {
6062
}
6163
}
6264

63-
/* https://www.geeksforgeeks.org/dsa/introduction-to-monotonic-stack-2/ */
65+
/* Reference: https://www.geeksforgeeks.org/dsa/introduction-to-monotonic-stack-2/ */

0 commit comments

Comments
 (0)