Tuesday, June 11, 2013

Leetcode: Container With Most Water in C++



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.

Solution:
int maxArea(vector<int> &height) {
        int max = 0;
        int len =height.size();
        int start =0;
        int end =len-1;
        while(start<end)
        {
            int curL = height[start];
            int curR = height[end];
            int area = (end-start)*min(curL, curR);
            if(area>max)
            max = area;
            if(curL>curR)
            {
                while(end>start&&height[end]<=curR)
                end--;
            }
            else
            {
                while(end>start&&height[start]<=curL)
                 start++;
            }
        }
        return max;
    }

No comments:

Post a Comment