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.
Above is a histogram where width of each bar is 1, given height =[2,1,5,6,2,3]
.
思路:用动态规划。
法I:首先想到用两个数组,分别存储向左最大延伸位置以及向右最大延伸位置,这种方法要遍历两边,且空间复杂度O(n)+O(n)
法II:用stack的栈顶元素指示所要计算的height,左界是栈顶第二个元素+1位置(因为只有栈顶永远是栈中高度最高的元素),右界是当前元素-1位置(当前元素比栈顶元素低的情况下)。当当前元素高度>= 栈顶元素高度,入栈,i++;当当前元素高度<栈顶元素高度,出栈,计算当前面积,i不增加。
class Solution { public int largestRectangleArea(int[] heights) { Stack<Integer> st = new Stack<Integer>(); if(heights.length == 0) return 0; int leftIndex; int topIndex; int area; int maxArea = 0; int i = 0; while(i < heights.length){ if(st.empty() || heights[i] >= heights[st.peek()]){ st.push(i); i++; } else{ topIndex = st.peek(); st.pop(); leftIndex = st.empty()?0:st.peek()+1; //如果是空,说明从头开始的所有高度都比heights[topIndex]高 area = ((i-1)-leftIndex + 1) * heights[topIndex]; if(area > maxArea) maxArea = area; } } while(!st.empty()){ //没有比栈顶元素小的元素让它出栈 topIndex = st.peek(); st.pop(); leftIndex = st.empty()?0:st.peek()+1; area = ((i-1)-leftIndex + 1) * heights[topIndex]; if(area > maxArea) maxArea = area; } return maxArea; } }