-
Notifications
You must be signed in to change notification settings - Fork 40
/
Copy pathLargestRectangleInHistogram.cpp
127 lines (120 loc) · 3.13 KB
/
LargestRectangleInHistogram.cpp
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
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
//84. Largest Rectangle in Histogram
//Given an array of integers heights representing the histogram's bar height where the width of each bar is 1, return the area of the largest rectangle in the histogram.
//LeetCode Url:https://leetcode.com/problems/largest-rectangle-in-histogram/description/
//SOLUTION
class Solution {
/*private:
vector<int> nextsmallerelement(vector<int>arr,int n){
stack<int>s;
s.push(-1);
vector<int>ans(n);
for(int i=n-1;i>=0;i--){
int curr = arr[i];
while(s.top() != -1 && arr[s.top() >= curr]){
s.pop();
if(s.empty()){
ans[i]=arr[i];
s.push(arr[i]);
}else{
ans[i] = s.top();
s.push(i);
}
}
}
return ans;
}
vector<int> prevsmallerelement(vector<int>arr,int n){
stack<int>s;
s.push(-1);
vector<int>ans(n);
for(int i=0;i<n;i++){
int curr = arr[i];
while(s.top() != -1 && arr[s.top() >= curr]){
s.pop();
if(s.empty()){
ans[i]=arr[i];
s.push(arr[i]);
}else{
ans[i] = s.top();
s.push(i);
}
}
}
return ans;
}
public:
int largestRectangleArea(vector<int>& heights) {
int n = heights.size();
vector<int> next(n);
next = nextsmallerelement(heights,n);
vector<int> prev(n);
prev = prevsmallerelement(heights,n);
int area = 0;
for(int i=0;i<n;i++){
int l = heights[i];
if(next[i] == -1){
next[i]=n;
}
int b = next[i]-prev[i]-1;
int newarea = l*b;
area = max(area,newarea);
}
return area;
}*/
vector<int> nextsmall(vector<int>& arr,int n){
stack<int> s;
s.push(-1);
vector<int> ans(n);
for(int i=arr.size()-1;i>=0;i--){
while(s.top()!=-1&&arr[s.top()]>=arr[i])
s.pop();
if(s.empty()){
ans[i]=arr[i];
s.push(arr[i]);
}
else
{
ans[i]=s.top();
s.push(i);
}
}
return ans;
}
vector<int> prevsmall(vector<int>& arr,int n){
stack<int> s;
s.push(-1);
vector<int> ans(n);
for(int i=0;i<n;i++){
while(s.top()!=-1&&arr[s.top()]>=arr[i])
s.pop();
if(s.empty()){
ans[i]=arr[i];
s.push(arr[i]);
}
else
{
ans[i]=s.top();
s.push(i);
}
}
return ans;
}
public:
int largestRectangleArea(vector<int>& heights) {
int area=0;
int n =heights.size();
vector<int> next(n);
vector<int> prev(n);
next=nextsmall(heights,n);
prev=prevsmall(heights,n);
for(int i=0;i<n;i++){
int l=heights[i];
if(next[i]==-1)
next[i]=n;
int b=next[i]-prev[i]-1;
int newarea=l*b;
area=max(newarea,area);
}
return area;
}
};