思路:c++
使用單調棧計算每一個位置左邊第一個比它矮的位置和右邊第一個比它矮的位置便可。spa
實現:code
1 #include <bits/stdc++.h> 2 using namespace std; 3 class Solution 4 { 5 public: 6 int largestRectangleArea(vector<int>& heights) 7 { 8 int n = heights.size(); 9 vector<int> l(n, -1); 10 stack<int> s; 11 s.push(0); 12 for (int i = 1; i < n; i++) 13 { 14 if (heights[s.top()] < heights[i]) 15 { 16 l[i] = s.top(); 17 s.push(i); 18 } 19 else 20 { 21 while (!s.empty() && heights[s.top()] >= heights[i]) 22 s.pop(); 23 if (!s.empty()) l[i] = s.top(); 24 s.push(i); 25 } 26 } 27 while (!s.empty()) s.pop(); 28 s.push(n - 1); 29 vector<int> r(n, n); 30 for (int i = n - 2; i >= 0; i--) 31 { 32 if (heights[s.top()] < heights[i]) 33 { 34 r[i] = s.top(); 35 s.push(i); 36 } 37 else 38 { 39 while (!s.empty() && heights[s.top()] >= heights[i]) 40 s.pop(); 41 if (!s.empty()) r[i] = s.top(); 42 s.push(i); 43 } 44 } 45 int ans = 0; 46 for (int i = 0; i < n; i++) 47 { 48 ans = max(ans, heights[i] * (r[i] - l[i] - 1)); 49 } 50 return ans; 51 } 52 }; 53 int main() 54 { 55 int a[] = {2, 1, 5, 6, 2, 3}; 56 vector<int> v(a, a + 6); 57 cout << Solution().largestRectangleArea(v) << endl; 58 return 0; 59 }