84. The largest rectangle in the histogram (difficulty)

Ideas:

The meaning of the question can be understood as comparing whether the current one is smaller than the previous one, if larger, then continue, if smaller, remove the previous one, and continue to compare.

It's easy to think of using a monotonic stack

 

 

Code:

class Solution {
    public int largestRectangleArea(int[] heights) {
		int n=heights.length,max=0;
		Deque<Integer> stack=new ArrayDeque<>();
		for(int i=0;i<=n;i++){
			//条件是:1.不为空  2.当前height小于栈顶端的height  3.i到了最后
			while(!stack.isEmpty()&&(i==n||heights[i]<heights[stack.peekLast()])){
                //先一步把值弹出,下面算的peekLast就是再前一个的下标
				int height=heights[stack.removeLast()];
				int width=stack.isEmpty()?i:i-1-stack.peekLast();
				max=Math.max(max,height*width);
			}
			//若不满足while的条件,就把值压入栈中(heights[i]>heights[stack.peek()])
			stack.addLast(i);
		}
		return max;
    }
}

 

break down:

1) Use ArrayDeque instead of ArrayList, or LinkedList, or Stack

The reason is that ArrayDeque and ArrayList are in the form of arrays, while LinkedList is in the form of linked lists, and Stack is not recommended in Java (see another blog post https://blog.csdn.net/di_ko/article/details/ 115004162 )

 

2)

int height=heights[stack.removeLast()];
int width=stack.isEmpty()?i:i-1-stack.peekLast();

These few lines of code are actually somewhat abbreviated, the original version is:

int height=heights[stack.peekLast()];
int width=stack.isEmpty()?i:i-stack.peekLast();
stack.removeLast();

 

3) The following code outside the while loop is actually a bit simpler

stack.addLast(i);

original version:

whie(...){
	stack.addLast(i);
}

if(heights[i]<heights[stack.peekLast()]){
	stack.addLast(i);
}

 

Guess you like

Origin blog.csdn.net/di_ko/article/details/115002489