标签:style blog color io ar for div sp log
---恢复内容开始---
1 class Solution { 2 public: 3 int largestRectangleArea(vector<int> &height) { 4 int n = height.size(); 5 if(n == 0) 6 { 7 return 0; 8 } 9 vector<int> leftMax(n); 10 vector<int> rightMax(n); 11 stack<int> s; 12 int i; 13 for(i = 0 ; i < n ; ++i) 14 { 15 leftMax[i] = 0; 16 if(i > 0) 17 { 18 int pre = -1; 19 while(!s.empty()) 20 { 21 int tmp = s.top(); 22 if(height[tmp] >= height[i]) 23 { 24 s.pop(); 25 } 26 else 27 { 28 pre = tmp; 29 break; 30 } 31 } 32 s.push(i); 33 leftMax[i] = i - pre - 1; 34 } 35 else 36 { 37 s.push(i); 38 } 39 } 40 stack<int> s1; 41 for(i = n-1 ; i >= 0 ; --i) 42 { 43 rightMax[i] = 0; 44 if(i < n-1) 45 { 46 int next = n; 47 while(!s1.empty()) 48 { 49 int tmp = s1.top(); 50 if(height[tmp] >= height[i]) 51 { 52 s1.pop(); 53 } 54 else 55 { 56 next = tmp; 57 break; 58 } 59 } 60 s1.push(i); 61 rightMax[i] = next - i - 1; 62 } 63 else 64 { 65 s1.push(i); 66 } 67 } 68 int res = INT_MIN; 69 for(i = 0 ; i < n ; ++i) 70 { 71 res = max(res,(leftMax[i]+rightMax[i]+1)*height[i]); 72 } 73 return res; 74 } 75 };
主要目的是记录左边以及右边比当前元素大的元素个数
---恢复内容结束---
LeetCode--Largest Rectangle in Histogram
标签:style blog color io ar for div sp log
原文地址:http://www.cnblogs.com/cane/p/3961689.html