Skip to content

Instantly share code, notes, and snippets.

@safeng
Created November 15, 2013 03:46
Show Gist options
  • Save safeng/7478739 to your computer and use it in GitHub Desktop.
Save safeng/7478739 to your computer and use it in GitHub Desktop.
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) {
// IMPORTANT: Please reset any member data you declared, as
// the same Solution instance will be reused for each test case.
size_t i = 0, j = height.size()-1;
size_t maxSize = 0;
while(i<j)
{
size_t curSize = 0;
if(height[i]<height[j])
{
curSize = height[i]*(j-i);
if(curSize > maxSize)
maxSize = curSize;
++i;
}else
{
curSize = height[j]*(j-i);
if(curSize > maxSize)
maxSize = curSize;
j--;
}
}
return (int)maxSize;
}
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment