Skip to content

Commit d8084c7

Browse files
authored
84. Largest Rectangle in Histogram
1 parent cc488f2 commit d8084c7

File tree

1 file changed

+67
-0
lines changed

1 file changed

+67
-0
lines changed

84. Largest Rectangle in Histogram

+67
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,67 @@
1+
//here we have to learn two more quentions first ...
2+
//Which are most important in Stack
3+
// 1.next Smaller Element
4+
//2. prev Smaller Element
5+
6+
//then we will be able to solve it
7+
//Formula----
8+
// area = length * width;
9+
10+
11+
class Solution {
12+
public:
13+
vector<int>nextSmallerElement(vector<int>& input){
14+
stack<int>s;
15+
s.push(-1);
16+
vector<int>ans(input.size());
17+
for(int i=input.size()-1;i>=0;i--){
18+
int curr = input[i];
19+
while(s.top()!= -1 && input[s.top()] >= curr){
20+
s.pop();
21+
}
22+
//chota mil chuka hai store ans
23+
ans[i] = s.top();
24+
//push kardo element ko
25+
s.push(i);
26+
}
27+
return ans;
28+
}
29+
vector<int>prevSmallerElement(vector<int>& input){
30+
stack<int>s;
31+
s.push(-1);
32+
vector<int>ans(input.size());
33+
//left to right
34+
for(int i=0;i<input.size();i++){
35+
int curr = input[i];
36+
37+
while(s.top()!= -1 && input[s.top()] >= curr){
38+
s.pop();
39+
}
40+
//chota element mil chuka hai
41+
ans[i] = s.top();
42+
//push kardo elment ko
43+
s.push(i);
44+
}
45+
return ans;
46+
}
47+
int largestRectangleArea(vector<int>& heights) {
48+
//prev smaller call
49+
vector<int>prev = prevSmallerElement(heights);
50+
//next smaller call
51+
vector<int>next = nextSmallerElement(heights);
52+
int MaxArea = INT_MIN;
53+
int size = heights.size();
54+
55+
for(int i=0;i<heights.size();i++){
56+
int length = heights[i];
57+
58+
if(next[i] == -1){
59+
next[i] = size;
60+
}
61+
int width = next[i] - prev[i] -1;
62+
int area = length * width;
63+
MaxArea = max(MaxArea,area);
64+
}
65+
return MaxArea;
66+
}
67+
};

0 commit comments

Comments
 (0)