Description
Given an array of integers heights representing the histogram’s bar height where the width of each bar is 1, return the area of the largest rectangle in the histogram.
Examples
Example 1:
Input: heights = [2,1,5,6,2,3]
Output: 10
Explanation: The above is a histogram where width of each bar is 1.
The largest rectangle is shown in the red area, which has an area = 10 units.
Example 2:
Input: heights = [2,4]
Output: 4
Constraints:
1 <= heights.length <= 105
0 <= heights[i] <= 104
Solution
一开始我以为要用动态规划,但规划了半天都没规划出来,还是用简单的 O ( n 2 ) O(n^2) O(n2)方法吧
对每个位置都计算以该高度为长方形的高,能拓展出去的最大面积
有一个需要注意的点
- 当height[i] ==height[i - 1]的时候,是不用重复计算的,否则会Time Limited Exceeded
还有一个可以改进的点,和字符串匹配的kwp算法比较接近,预存一个position[]数组,position[i]表示height[i]对应的长方形最左侧位置。(代码2)
代码1
class Solution {
public int largestRectangleArea(int[] heights) {
int answer = 0;
int i, j;
for(i = 0; i < heights.length; i++){
if(i > 0 && heights[i] == heights[i - 1])
continue; // key point
int temp = heights[i];
for(j = i; j >= 0; j--){
if (heights[i] > heights[j])
break;
}
temp = temp + (i - j - 1) * heights[i];
for(j = i; j < heights.length; j++){
if (heights[i] > heights[j])
break;
}
temp = temp + (j - i - 1) * heights[i];
if(answer < temp)
answer = temp;
}
return answer;
}
}
代码2
class Solution {
public int largestRectangleArea(int[] heights) {
int answer = 0;
int[] position = new int[heights.length];
int i, j;
for(i = 0; i < heights.length; i++){
if(i > 0 && heights[i] == heights[i - 1]){
position[i] = position[i - 1];
continue; // key point
}
int temp = heights[i];
for(j = i - 1; j >= 0; j--){
if (heights[i] > heights[j])
break;
else
j = position[j] + 1;
}
position[i] = j;
temp = temp + (i - j - 1) * heights[i];
for(j = i + 1; j < heights.length; j++){
if (heights[i] > heights[j])
break;
}
temp = temp + (j - i - 1) * heights[i];
if(answer < temp)
answer = temp;
}
return answer;
}
}