-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathLargestRectangleInHistogram.java
More file actions
43 lines (43 loc) · 1.18 KB
/
LargestRectangleInHistogram.java
File metadata and controls
43 lines (43 loc) · 1.18 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
import java.util.*;
public class LargestRectangleInHistogram {
public static int maxArea(int arr[]){
int arr1[]=new int[arr.length];
Stack<Integer> s = new Stack<>();
int nsr[]=new int[arr.length];
int nsl[]=new int[arr.length];
for(int i=arr.length-1;i>=0;i--){
while(!s.isEmpty()&&arr[s.peek()]>=arr[i]){
s.pop();
}
if(s.isEmpty()){
nsr[i]=arr.length;
}else{
nsr[i]=s.peek();
}
s.push(i);
}
s.clear();
for(int i=0;i<arr.length;i++){
while(!s.isEmpty()&&arr[s.peek()]>=arr[i]){
s.pop();
}
if (s.isEmpty()){
nsl[i]=-1;
}else{
nsl[i]=s.peek();
}
s.push(i);
}
int max=0;
for(int i=0;i<arr.length;i++){
int width=nsr[i]-nsl[i]-1;
int area=arr[i]*width;
max=Math.max(max,area);
}
return max;
}
public static void main(String[] args) {
int arr[]={2,1,5,6,2,3};
System.out.println(maxArea(arr));
}
}