LeetCode: Container With Most Water

Given n non-negative integers a1a2, ..., an, where each represents a point at coordinate (iai). n vertical lines are drawn such that the two endpoints of line i is at (iai) 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.

Start from the two ends to the middle, hence the distance between two lines are smaller and smaller, if we want to enlarge the volume, we must choose the line that are longer than current ones.

class Solution {
public:
    int maxArea(vector<int> &height) {
        // Start typing your C/C++ solution below
        // DO NOT write int main() function
        int max = 0;
        int j = height.size() - 1;
        int i = 0;
        while(i < j){
            int v = (j - i) * min(height[i], height[j]);
            if(v > max){max = v;}
            if(height[i] < height[j]){
                while(height[i] > height[++i]);
            }
            else{
                while(height[j] > height[--j]);
            }
        }
        return max;
    }
    inline int min(int a, int b){
        return a < b? a: b;
    }
};


你可能感兴趣的:(LeetCode: Container With Most Water)