-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathMaxRectangleAreaInHistrogram.java
More file actions
53 lines (44 loc) · 1.11 KB
/
MaxRectangleAreaInHistrogram.java
File metadata and controls
53 lines (44 loc) · 1.11 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
45
46
47
48
49
50
51
52
53
package com.duke.stack;
import java.util.Stack;
public class MaxRectangleAreaInHistrogram {
public static void main(String[] args) {
int[] a = { 3, 2, 5, 6, 1, 4, 4 };
// int a[] = { 6, 2, 5, 4, 5, 1, 6 };
maxRectangleArea(a);
}
private static void maxRectangleArea(int[] a) {
Stack<Integer> stack = new Stack<>();
if (a == null || a.length == 0) {
return;
}
int maxArea = 0;
int i = 0;
int area = 0;
while (i < a.length) {
if (stack.isEmpty() || a[stack.peek()] <= a[i]) {
stack.push(i);
i++;
} else {
int top = stack.pop();
if (!stack.isEmpty()) {
area = a[top] * (i - stack.peek() - 1);
} else {
area = a[top] * (i-top);
System.out.println(area);
}
maxArea = Math.max(maxArea, area);
}
}
while (!stack.isEmpty()) {
int top = stack.pop();
if (!stack.isEmpty()) {
area = a[top] * (i - stack.peek() - 1);
} else {
area = a[top] * (i-top);
System.out.println(area);
}
maxArea = Math.max(maxArea, area);
}
System.out.println("Max Histrogram Area:"+maxArea);
}
}