Container With Most Water

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.

class Solution {
public:
    int maxArea(vector<int>& height) {
        //sort(height.begin(), height.end());
        int n = height.size();
        if(n < 2)   return 0;

        int maxArea = 0;
        int st = 0, en = n - 1;
        while(st < en){
            int minheight = min(height[st], height[en]);
            int area = (en - st) * minheight;
            maxArea = max(area, maxArea);
            if(minheight == height[st]){
                st++;
            }else{
                en--;
            }
        }
        return maxArea;
    }
};

results matching ""

    No results matching ""