# 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

## 题解

 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 };
View Code

 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 };
View Code

 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 };
View Code

 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 };
View Code

posted @ 2019-02-22 21:32  TobicYAL  阅读(205)  评论(0编辑  收藏  举报