liuguanyu / quiz-every-meeting

8 stars 0 forks source link

2018-05-31 #10

Open wuxueguang opened 6 years ago

wuxueguang commented 6 years ago

原地址

给定 n 个非负整数 a1,a2,...,an,每个数代表坐标中的一个点 (i, ai) 。画 n 条垂直线,使得垂直线 i 的两个端点分别为 (i, ai) 和 (i, 0)。找出其中的两条线,使得它们与 x 轴共同构成的容器可以容纳最多的水。

注意:你不能倾斜容器,n 至少是2。

wuxueguang commented 6 years ago
/**
 * @param {number[]} height
 * @return {number}
 */
var maxArea = function(height) {
    let l = height.length;
    let baseHeight = height[0] > height[l - 1] ? height[l - 1] : height[0];
    let baseErea = (l - 1) * baseHeight;

    height.forEach((h, i) => {
        if(h > baseHeight){
            let d = Math.ceil(baseErea / h);

            if((i + d) < l){
                for(let j = i + d; j < l; j++){
                    baseErea = height[j] >= h ? (j - i) * h : baseErea;
                }
            }

            if((i - d) > -1){
                for(let k = i - d; k > -1; k--){
                    baseErea = height[k] >= h ? (i - k) * h : baseErea;
                }
            }
        }   
    });

    return baseErea;
};
liuguanyu commented 6 years ago
int maxArea(vector<int> &height) {  
    int start =0;    
      int end = height.size()-1;    
     int maxV = INT_MIN;    
      while(start<end)    
      {    
        int contain = min(height[end], height[start]) * (end-start);    
        maxV = max(maxV, contain);    
        if(height[start]<= height[end])    
        {    
          start++;    
        }    
        else    
        {    
          end--;    
        }    
      }    
      return maxV;    
}
liuzhengbo commented 6 years ago
var maxArea = function(height) {
    const length = height.length;
    let start = 0;
    let end = length - 1;

    let max = 0;
    while(start < end) {
        const rect1 = Math.min(height[start], height[end]);
        const rect2 = end - start;
        const area = rect1 * rect2;
        max = Math.max(area, max);

        height[start] < height[end] ? ++start : --end;
    }

    return max;
};