leetcode_84_柱状图中最大的矩形

leetcode_84_柱状图中最大的矩形_第1张图片
leetcode_84_柱状图中最大的矩形_第2张图片

class Solution {
    	public static int largestRectangleArea(int[] heights) {
		int length = heights.length;
		if (length == 0)
			return 0;
		if (length == 1)
			return heights[0];

		int[] rightMin = new int[length];
		int[] leftMin = new int[length];

		Stack<Integer> stk = new Stack<Integer>();
		for (int i = length - 1; i >= 0; i--) {
			while (!stk.isEmpty() && heights[i] <= heights[stk.peek()]) {
				stk.pop();
			}
			rightMin[i]=stk.isEmpty()?length:stk.peek();
			stk.push(i);
		}
	
		stk.clear();

		for (int i = 0; i < length; i++) {
			while (!stk.isEmpty() && heights[i] <= heights[stk.peek()]) {
				stk.pop();
			}
			leftMin[i]=stk.isEmpty()?-1:stk.peek();
			stk.push(i);
		}
	
		int maxArea = 0;

		for (int i = 0; i < heights.length; i++) {
			int l = leftMin[i];
			int r = rightMin[i];
			int width = r - l - 1;
			maxArea = Math.max(maxArea, width * heights[i]);
		}

		return maxArea;

	}
}

你可能感兴趣的:(数据结构与算法,栈)