[InterviewBit] Largest Rectangle in Histogram

Largest Rectangle in Histogram

  • Time : O(n)
  • Space : O(n)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
int Solution::largestRectangleArea(vector<int> &A) {
int res = 0, n = A.size();
vector<pair<int, int>> st;
for(int i = 0; i < n; i++) {
if(st.empty() or st.back().second < A[i]) st.push_back({i,A[i]});
else {
int p = i;
while(st.back().second >= A[i]) {
p = st.back().first;
res = max(res, (i - st.back().first) * st.back().second);
st.pop_back();
}
st.push_back({p,A[i]});
}
}
for(int i = 0; i < st.size(); i++) {
auto [p, h] = st[i];
res = max(res, (n-p) * h);
}
return res;
}

Author: Song Hayoung
Link: https://songhayoung.github.io/2022/08/30/PS/interviewbit/largest-rectangle-in-histogram/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.