-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathLargestAreaHistogram.java
More file actions
44 lines (37 loc) · 1.38 KB
/
LargestAreaHistogram.java
File metadata and controls
44 lines (37 loc) · 1.38 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
32
33
34
35
36
37
38
39
40
41
42
43
44
// Largest Rectangle in Histogram problem
import java.util.*;
public class LargestAreaHistogram {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.print("Enter number of bars in histogram: ");
int n = sc.nextInt();
int[] heights = new int[n];
System.out.println("Enter the heights of the bars:");
for (int i = 0; i < n; i++) {
heights[i] = sc.nextInt();
}
int maxArea = largestRectangleArea(heights);
System.out.println("Largest rectangle area in the histogram: " + maxArea);
}
public static int largestRectangleArea(int[] heights) {
int n = heights.length;
Stack<Integer> stack = new Stack<>();
int maxArea = 0;
for (int i = 0; i <= n; i++) {
int currHeight = (i == n) ? 0 : heights[i];
while (!stack.isEmpty() && currHeight < heights[stack.peek()]) {
int height = heights[stack.pop()];
int width;
if (stack.isEmpty()) {
width = i;
} else {
width = i - stack.peek() - 1;
}
int area = height * width;
maxArea = Math.max(maxArea, area);
}
stack.push(i);
}
return maxArea;
}
}