[AlgoExpert] Largest Rectangle Under Skyline

Largest Rectangle Under Skyline

  • 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
#include <vector>
using namespace std;

int largestRectangleUnderSkyline(vector<int> buildings) {
vector<pair<int, int>> st{{-1,0}};
int res = 0, n = buildings.size();
for(int i = 0; i < n; i++) {
int p = i;
while(!st.empty() and st.back().second >= buildings[i]) {
res = max(res, st.back().second * (i - st.back().first));
p = st.back().first;
st.pop_back();
}
st.push_back({p, buildings[i]});
}
for(int i = 0; i < st.size(); i++) {
res = max(res, st[i].second * (n - st[i].first));
}
return res;
}
Author: Song Hayoung
Link: https://songhayoung.github.io/2022/05/09/PS/AlgoExpert/largest-rectangle-under-skyline/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.