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.
update clean code solution 2022.02.19
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 class Solution {public : int largestRectangleArea (vector<int >& h) { vector<pair<int , int >> st; int area = 0 ; for (int i = 0 ; i < h.size (); i++) { int lastIndex = i; while (!st.empty () and st.back ().second > h[i]) { area = max (area, st.back ().second * (i - st.back ().first)); lastIndex = st.back ().first; st.pop_back (); } st.push_back ({lastIndex, h[i]}); } while (!st.empty ()) { area = max (area, (int )(st.back ().second * (h.size () - st.back ().first))); st.pop_back (); } return area; } };
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 class Solution {public : int largestRectangleArea (vector<int >& h) { vector<pair<int , int >> st {{0 ,-1 }}; int res = 0 ; for (int i = 0 ; i < h.size (); i++) { while (!st.empty () and st.back ().first >= h[i]) st.pop_back (); st.push_back ({h[i], i}); if (h[i]) { for (int j = 1 ; j < st.size (); j++) { res = max (res, (i - st[j-1 ].second) * st[j].first); } } } return res; } };