[leetcode]Container With Most Water 和Largest Rectangle in Histogram

这两题看起来有点像,但是实际上是完全不一样的,区别在于:

The "Container With Most Water" solution will allow the water to rise above intermediate positions. With the "largest rectangle" problem, the rectangle cannot rise above intermediate bars.
也就是说 Container With Most Water只考虑左右边界,[i,j]范围内的Area = min(height[i],height[j]) * (j-i); Largest Rectangle in Histogram,高度最小值为[i,j]范围内所有高度的最小值。后者比前者要难很多
1. Container With Most Water
对于这题,考虑左右边界[i,j] ,当height[i]
代码:
public class Solution {
    public int min(int i,int j){
        return imax) max = area;
            if(height[i]
 
Largest Rectangle in Histogram 
代码如下:
public int largestRectangleArea(int[] height) {
        // Note: The Solution object is instantiated only once and is reused by each test case.
        if(height == null) return 0;
        int len = height.length;
        Stack stack = new Stack();
        Stack width = new Stack();//记录向左可以扩展的宽度
        int max = 0;
        stack.push(0);
        width.push(0);
        
        int h;
        for(int i = 0;i<=len;i++){ 
            if(i == len) h = 0;
            else h = height[i];
            int wid = 0;
            while(hh的右边界已经找到了
                int top = stack.pop();
                wid += width.pop();
                max = Math.max(max,top*wid);
                }
            stack.push(h);
            width.push(Math.max(wid+1,1));//每次加入stack的时候,他的左边界就已经确定了
           
        }
        return max;
    }
 
 

你可能感兴趣的:(找工作系列之-刷题记录,数据结构与算法)