19.2.22 [LeetCode 84] Largest Rectangle in Histogram
Given n non-negative integers representing the histogram's bar height where the width of each bar is 1, find the area of largest rectangle in the histogram.
Above is a histogram where width of each bar is 1, given height = [2,1,5,6,2,3]
.
The largest rectangle is shown in the shaded area, which has area = 10
unit.
Example:
Input: [2,1,5,6,2,3]
Output: 10
题意
找到直方图中最大的长方形
题解
首先是硬核暴力解法,当然很慢啦
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
1 class Solution { 2 public: 3 int largestRectangleArea(vector<int>& heights) { 4 int n = heights.size(), ans = 0; 5 vector<int>dp(n, INT_MAX); 6 for (int i = 1; i <= n; i++) { 7 for (int j = 0; j <= n - i; j++) { 8 int e = i + j - 1; 9 if (i == 1) 10 dp[j] = heights[j]; 11 else 12 dp[j] = min(heights[e], dp[j]); 13 ans = max(ans, i*dp[j]); 14 } 15 } 16 return ans; 17 } 18 };
换了一种也没好多少
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
1 class Solution { 2 public: 3 int largestRectangleArea(vector<int>& heights) { 4 int ans = 0, n = heights.size(); 5 for (int i = 0; i < n; i++) { 6 int s = i, e = i, h = heights[i]; 7 while (s>=0 && heights[s] >= h) 8 s--; 9 while (e<n && heights[e] >= h) 10 e++; 11 ans = max(ans, (e - s - 1)*h); 12 } 13 return ans; 14 } 15 };
加个特判,还是不行,看来是根本上的思路有问题
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
1 class Solution { 2 public: 3 int largestRectangleArea(vector<int>& heights) { 4 int ans = 0, n = heights.size(); 5 for (int i = 0; i < n; i++) { 6 int s = i, e = i, h = heights[i]; 7 if ((long)h*(long)n <= ans)continue; 8 while (s>=0 && heights[s] >= h) 9 s--; 10 while (e<n && heights[e] >= h) 11 e++; 12 ans = max(ans, (e - s - 1)*h); 13 } 14 return ans; 15 } 16 };
好吧……其实也没什么跳脱的思路,算是剪枝的思想,遍历数组,求以当前为右边界的最大矩形。剪枝剪掉的部分是:只算后面那根条比自己矮的那些位置的情况,因为不然只算后面那根条的情况就能包括当前算出来的最大矩形
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
1 class Solution { 2 public: 3 int largestRectangleArea(vector<int>& heights) { 4 int ans = 0, n = heights.size(); 5 for (int i = 0; i < n; i++) { 6 if (i != n - 1 && heights[i] <= heights[i + 1])continue; 7 int h = heights[i]; 8 for (int j = i; j >= 0; j--) { 9 h = min(h, heights[j]); 10 ans = max(h*(i - j + 1), ans); 11 } 12 } 13 return ans; 14 } 15 };
注定失败的战争,也要拼尽全力去打赢它;
就算输,也要输得足够漂亮。