leetcode@ [84/85] Largest Rectangle in Histogram & Maximal Rectangle
https://leetcode.com/problems/largest-rectangle-in-histogram/
https://leetcode.com/problems/maximal-rectangle/
1 class Solution { 2 public: 3 int largestRectangleArea2(vector<int> height) { 4 if(height.size()==0) return 0; 5 6 int ret = numeric_limits<int>::min(); 7 for(int i=0;i<height.size();++i) { 8 int area = height[i]; 9 int left = i-1, right = i+1; 10 for(;left>=0 && height[i]<=height[left];--left) area += height[i]; 11 for(;right<height.size() && height[i]<=height[right];++right) area += height[i]; 12 ret = max(ret, area); 13 } 14 return ret; 15 } 16 int largestRectangleArea(vector<int>& height) { 17 //return largestRectangleArea2(height); 18 if(height.size()==0) return 0; 19 20 height.push_back(-1); 21 stack<int> st; 22 int ret = numeric_limits<int>::min(), hId, width, area, start; 23 for(int i=0;i<height.size();++i) { 24 if(st.empty()) { 25 st.push(i); 26 start = st.top(); 27 } 28 if(height[st.top()] < height[i]) st.push(i); 29 while(!st.empty() && height[st.top()] > height[i]) { 30 hId = st.top(); st.pop(); 31 width = st.empty()? i-start: i-st.top()-1; 32 ret = max(ret, width * height[hId]); 33 } 34 st.push(i); 35 } 36 return ret; 37 } 38 };
1 class Solution { 2 public: 3 void clear(vector<int> &vec) { 4 for(int i=0;i<vec.size();++i) vec[i] = 0; 5 } 6 void clearStack(stack<int> &st) { 7 while(!st.empty()) st.pop(); 8 } 9 int largestRectangleArea(vector<int>& height) { 10 if(height.size()==0) return 0; 11 12 height.push_back(-1); 13 stack<int> st; 14 int ret = numeric_limits<int>::min(), hId, width, area, start; 15 for(int i=0;i<height.size();++i) { 16 if(st.empty()) { 17 st.push(i); 18 start = st.top(); 19 } 20 if(height[st.top()] < height[i]) st.push(i); 21 while(!st.empty() && height[st.top()] > height[i]) { 22 hId = st.top(); st.pop(); 23 width = st.empty()? i-start: i-st.top()-1; 24 ret = max(ret, width * height[hId]); 25 } 26 st.push(i); 27 } 28 return ret; 29 } 30 int maximalRectangle(vector<vector<char>>& matrix) { 31 if(matrix.size() == 0) return 0; 32 33 vector<int> height(matrix[0].size()); 34 35 int ret = numeric_limits<int>::min(), start; 36 for(int i=0;i<matrix.size();++i) { 37 for(int j=0;j<matrix[0].size();++j) { 38 if(matrix[i][j]=='1') height[j]++; 39 else height[j] = 0; 40 } 41 42 ret = max(ret, largestRectangleArea(height)); 43 } 44 45 return ret; 46 } 47 };