首页 > 代码库 > Container With Most Water <leetcode>

Container With Most Water <leetcode>

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.

 

 1 class Solution { 2 public: 3     int maxArea(vector<int> &h) { 4         // Start typing your C/C++ solution below 5         // DO NOT write int main() function 6         int res=0; 7         int n = h.size(); 8         int l=0,r=n-1; 9         while(l<r)10         {11             res=max(res,min(h[l],h[r])*(r-l));12             if (h[l]<h[r])13             {14                 int k=l;15                 while(k<r&&h[k]<=h[l])16                     k++;17                 l=k;18                 }19             else20             {21                 int k=r;22                 while(k>l&&h[k]<=h[r])23                     k--;24                 r=k;25              }26         }27         return res;28     }29 };

 

Container With Most Water <leetcode>