思路一:
前一個柱子若大於後一個柱子,則它大於的部分其實對於後一個柱子後面的柱子與他形成的矩形大小沒有關係
基於此,每次遍歷回去更新,比較暴力,最後要優化一下全是同一高度的情況,即整個圖形爲一個矩形。
class Solution {
public int largestRectangleArea(int[] heights) {
int flag=0;
for(int i=0;i<heights.length-1;i++){
if(heights[i]==heights[i+1]){
continue;
}else{
flag=1;
}
}
if(flag==0){
if(heights.length==0){
return 0;
}else{
return heights[0]*heights.length;
}
}
int[]hei = new int[heights.length];
int Max=0;
for(int i = 0;i<heights.length;i++){
hei[i]=heights[i];
if(Max<heights[i]){
Max=heights[i];
}
for(int j=i-1;j>=0;j--){
if(hei[j]<=heights[i]){
if(hei[j]*(i-j+1)>Max){
Max = hei[j]*(i-j+1);
}
}else{
hei[j] = heights[i];
if(hei[j]*(i-j+1)>Max){
Max=hei[j]*(i-j+1);
}
}
if(hei[j]>Max){
Max = hei[j];
}
}
}
return Max;
}
}
思路二:
引用大佬的解釋(用棧 其實也用到上面那種方法的思想):
https://www.cnblogs.com/ganganloveu/p/4148303.html
自己的實現:
class Solution {
public int largestRectangleArea(int[] heights) {
Stack<Integer>stk = new Stack<Integer>();
int Max=0;
for(int i=0;i<heights.length;i++){
if(stk.empty()){
stk.push(heights[i]);
}else{
if(stk.peek()<=heights[i]){
stk.push(heights[i]);
}else{
int count = 0 ;
while(!stk.empty()&&stk.peek()>heights[i]){
count++;
if(Max<count*stk.peek()){
Max = count*stk.pop();
}else{
stk.pop();
}
}
while(count>=0){
stk.push(heights[i]);
count--;
}
}
}
}
//System.out.print(Max);
int len = stk.size();
for(int i=1;i<=len;i++){
if(stk.peek()*i>=Max){
Max = stk.pop()*i;
System.out.print(Max);
}else{
stk.pop();
}
}
return Max;
}
}