leetcode 柱状图中的最大矩形

 
  
public int largestRectangleArea(int[] heights) {
        if (heights == null || heights.length < 1)
            return 0;
 
        Stack stack = new Stack();
        stack.push(-1);
        int max = 0;
        for (int i = 0; i < heights.length; i++) {
            while (stack.peek() != -1 && heights[i] < heights[stack.peek()]) {
                int top = stack.pop();
                max = Math.max(max, (i - stack.peek() - 1) * heights[top]);
            }
            stack.push(i);
        }
        while (stack.peek() != -1) {
            int top = stack.pop();
            max = Math.max(max, (heights.length - 1 - stack.peek()) * heights[top]);
        }
        return max;
    }
public class Solution {
    public int largestRectangleArea(int[] height) {
        int n = height.length;
        int []h = new int[n+2];
        h[0] = h[n+1] = -1;
        for(int i=1;i<=n;i++)
            h[i] = height[i-1];
        int []left = new int[n+2];
        int []right = new int[n+2];
        for(int i=1;i<=n;i++){
            left[i] = i;
            right[i] = i;
        }
        for(int i=1;i<=n;i++){
            while(h[i]<=h[left[i]-1]){
                left[i] = left[left[i]-1];  //改变的值只有left[i],不涉及别的值
            }
        }
        for(int i=n;i>=1;i--){
            while(h[i]<=h[right[i]+1]){
                right[i] = right[right[i]+1];
            }
        }
        int res = 0 , cur = 0;
        for(int i=1;i<=n;i++){
            cur = (right[i]-left[i]+1)*h[i];
            if(cur>res)
                res = cur;
        }
        return res;
    }
}








你可能感兴趣的:(dp)