leetcode -- Largest Rectangle in Histogram TODO O(N)

时间:2021-12-11 12:48:05

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.

leetcode -- Largest Rectangle in Histogram TODO O(N)

Above is a histogram where width of each bar is 1, given height = [2,1,5,6,2,3].

leetcode -- Largest Rectangle in Histogram TODO O(N)

The largest rectangle is shown in the shaded area, which has area = 10 unit.

For example,
Given height = [2,1,5,6,2,3],
return 10.

本题思路和Trapping Rain Water差不多,计算每个idx的left bound 和right bound(两个bound都需大于height[idx])

时间复杂度为:O(n^2)

 public int largestRectangleArea(int[] height) {
// Start typing your Java solution below
// DO NOT write main() function
int len = height.length;
int[] area = new int[len]; for(int i = 0; i < len; i++){
int h = height[i]; int m = i - 1;
for(; m >= 0; m --){
if(height[m] < h){
break;
}
}
m ++; int n = i + 1;
for(; n < len; n ++){
if(height[n] < h){
break;
}
}
n --; int width = (n - m) + 1;
area[i] = h * width;
}
int max = 0;
for(int i = 0; i < len; i++){
if(area[i] > max){
max = area[i];
}
}
return max;
}

可以过小数据,大数据挂在输入[1,1,1,1,1,1........] ,说明有很多重复计算,做了一个简单改进,当前高度与上一个相同时,直接将area[i] = area[i-1](line 12-15)

 public int largestRectangleArea(int[] height) {
// Start typing your Java solution below
// DO NOT write main() function
int len = height.length;
int[] area = new int[len]; for(int i = 0; i < len; i++){
int h = height[i]; 12 if(i >= 1 && h == height[i - 1]){
13 area[i] = area[i - 1];
14 continue;
15 } int m = i - 1;
for(; m >= 0; m --){
if(height[m] < h){
break;
}
}
m ++; int n = i + 1;
for(; n < len; n ++){
if(height[n] < h){
break;
}
}
n --; int width = (n - m) + 1;
area[i] = h * width;
}
int max = 0;
for(int i = 0; i < len; i++){
if(area[i] > max){
max = area[i];
}
}
return max;
}