Skip to content

Commit 7f1c1c8

Browse files
committed
feat: implement LargestRectangleHistogram for calculating maximum rectangle area in a histogram
1 parent 3eb521b commit 7f1c1c8

1 file changed

Lines changed: 34 additions & 0 deletions

File tree

Lines changed: 34 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,34 @@
1+
import java.util.Stack;
2+
3+
public class LargestRectangleHistogram {
4+
public static int largestRectangleArea(int[] heights) {
5+
Stack<Integer> stack = new Stack<>();
6+
int maxArea = 0;
7+
int n = heights.length;
8+
9+
for (int i = 0; i <= n; i++) {
10+
// Use 0 height at end to flush stack
11+
int h = (i == n) ? 0 : heights[i];
12+
13+
while (!stack.isEmpty() && h < heights[stack.peek()]) {
14+
int height = heights[stack.pop()];
15+
int width;
16+
if (stack.isEmpty()) {
17+
width = i; // rectangle extends from 0 to i-1
18+
} else {
19+
width = i - stack.peek() - 1; // between previous smaller and i
20+
}
21+
maxArea = Math.max(maxArea, height * width);
22+
}
23+
stack.push(i);
24+
}
25+
26+
return maxArea;
27+
}
28+
29+
public static void main(String[] args) {
30+
int[] heights = {2, 1, 5, 6, 2, 3};
31+
int result = largestRectangleArea(heights);
32+
System.out.println("Largest Rectangle Area: " + result);
33+
}
34+
}

0 commit comments

Comments
 (0)