--

leetcode 011: container with most water



https://leetcode.com/problems/container-with-most-water/submissions/



problem:

Given n non-negative integers a1, a2, ..., an , where each represents a point at coordinate (i, ai). 
n vertical lines are drawn such that the two endpoints of line i is at (i, ai) and (i, 0). 
Find two lines, which together with x-axis forms a container, such that the container contains the most water.

Note: You may not slant the container and n is at least 2.
  
The above vertical lines are represented by array [1,8,6,2,5,4,8,3,7]. In this case, the max area of water (blue section) the container can contain is 49.




start code (c++)
 
class Solution {
public:
    bool isMatch(string s, string p) {
        
    }
};



solution:

我的思路:
i 从左往右遍历,j 从右往左遍历。
在 i 遍历过程当中,记录到目前为止的最大的 height[i], 然后忽略掉所有小于该值的 i 作为容器的左边栏。
在 j 遍历当中,记录到目前为止最大的 height[j], 然后忽略掉所有小于该值的 j 作为容器的右边栏。
同时对于 j, 如果出现了 某个 height[j] > height[i],那么可以忽略剩下的 j 的遍历了。



class Solution {
public:
    int maxArea(vector& height) {
        int maxVol = 0;
        int leftBarIdx = 0;
        int rightBarIdx = 0;

        // loop i from the left to right, j from right to left
        int highestI = 0;
        for (int i = 0; i < height.size() -1; i ++){
            if (highestI >= height[i])
                continue;
            highestI = height[i];
            int highestJ = -1;
            int noMoreCheck = 0;
            for (int j = height.size() -1; j > i; j--){
                if (noMoreCheck)
                    break;
                if (highestJ > height[j])
                    continue;
                highestJ = height[j];
                int vol;
                if (highestJ > height[i])
                    vol = (j -i) * height[i];
                else
                    vol = (j -i) * highestJ;
                if (maxVol < vol){
                    maxVol = vol;
                    leftBarIdx = i;
                    rightBarIdx = j;
                }
                if (height[j] >= height[i])
                    noMoreCheck = 1;
            }
        }
        return maxVol;
        
    }
};

另外一种巧妙的解法:
从两头逼近。
class Solution {
public:
    int maxArea(vector& height) {
        int l = 0;
        int h = height.size() -1;
        int max = 0;
        while (l < h){
            int vol = h - l;
            if (height[l] < height[h]){
                vol = vol * height[l];
                l ++;
            }else{
                vol = vol * height[h];
                h --;
            }
            if (max < vol)
                max = vol;
        }
        return max;
    }
};