forked from neiljaviya/hostel-app-ui
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathLargest_Rectangle_In_Histogram.java
More file actions
31 lines (27 loc) · 1.05 KB
/
Largest_Rectangle_In_Histogram.java
File metadata and controls
31 lines (27 loc) · 1.05 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
public class Largest_Rectangle_In_Histogram {
public int largestRectangleArea(int[] heights) {
//Initialising variables
int len = heights.length;
int maxArea = 0;
//Initialising stack
Stack<Integer> stack = new Stack<>();
//Iterating through the array
for (int i = 0; i <= len;) {
int h = (i == len ? 0 : heights[i]);
//Pushing to the stack if it is empty or if h is greater than the given value
if (stack.isEmpty() || h >= heights[stack.peek()]) {
stack.push(i);
i++;
}else {
//Calculating the width
int curHeight = heights[stack.pop()];
int rightBoundary = i - 1;
int leftBoundary = stack.isEmpty() ? 0 : stack.peek() + 1;
int width = rightBoundary - leftBoundary + 1;
maxArea = Math.max(maxArea, (curHeight * width));
}
}
//Returning the answer
return maxArea;
}
}