Skip to content

Commit c805e41

Browse files
committed
added largest-rectangle-in-histogram.java code
1 parent 009596a commit c805e41

File tree

1 file changed

+65
-0
lines changed

1 file changed

+65
-0
lines changed
Lines changed: 65 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,65 @@
1+
//Question : https://leetcode.com/problems/largest-rectangle-in-histogram/description/
2+
3+
class Solution {
4+
public int largestRectangleArea(int[] h) {
5+
6+
//monotonic stack
7+
8+
int n=h.length;
9+
int left[]=new int[n]; //left small elem's ind'
10+
int ryt[]=new int[n]; //ryt smaller elem's ind'
11+
12+
Stack<Integer> lin=new Stack<>(); //storing index in stacks
13+
Stack<Integer> rin=new Stack<>();
14+
15+
int ans[]=new int[n]; //ans array
16+
17+
//1.store each elem's ryt side next small elem index in ryt[]
18+
for(int i=0;i<n;i++)
19+
{
20+
//before add cur elem index to stack,
21+
//we check if its the ryt next small of elems in stack
22+
while( rin.size()>0 && h[i]< h[rin.peek()] )
23+
{
24+
ryt[rin.peek()]=i;
25+
rin.pop();
26+
}
27+
rin.push(i);
28+
}
29+
//if no small elem present in ryt, assign n.
30+
while(rin.size()>0)
31+
{
32+
ryt[rin.pop()]=n;
33+
}
34+
35+
36+
//2.store each elem's left side next small elem index in left[]
37+
for(int i=n-1;i>=0;i--)
38+
{
39+
//before add cur elem index to stack,
40+
//we check if its the left next small of elems in stack
41+
while( lin.size()>0 && h[i]<h[lin.peek()] )
42+
{
43+
left[lin.pop()]=i;
44+
}
45+
lin.push(i);
46+
}
47+
//if no small elem present in left, assign '-1'.
48+
while(lin.size()>0)
49+
{
50+
left[lin.pop()]=-1;
51+
}
52+
53+
54+
//3. calculate area of rectangle(i.e area=width*height)
55+
//store ans arr in left[] //height=value at an ind
56+
for(int i=0;i<n;i++)
57+
{
58+
int w=ryt[i]-left[i] - 1; //width
59+
ans[i]= w * h[i] ; //area
60+
}
61+
62+
//4. return max of ans arr(i.e...left[])
63+
return Arrays.stream(ans).max().getAsInt();
64+
}
65+
}

0 commit comments

Comments
 (0)