Skip to content

Instantly share code, notes, and snippets.

@luoxiaoxun
Created July 8, 2013 08:10
Show Gist options
  • Select an option

  • Save luoxiaoxun/5947051 to your computer and use it in GitHub Desktop.

Select an option

Save luoxiaoxun/5947051 to your computer and use it in GitHub Desktop.
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. Note: You may not slant the container.
C++:
class Solution {
public:
int maxArea(vector<int> &height) {
// Start typing your C/C++ solution below
// DO NOT write int main() function
int low=0;
int high=height.size()-1;
int ret=0;
while(low<high){
int area=(high-low)*min(height[low],height[high]);
ret=max(ret,area);
if(height[low]<=height[high]) low++;
else high--;
}
return ret;
}
};
Java:
public class Solution {
public int maxArea(int[] height) {
// Start typing your Java solution below
// DO NOT write main() function
int low=0;
int high=height.length-1;
int ret=0;
while(low<high){
int area=(high-low)*Math.min(height[low],height[high]);
ret=Math.max(ret,area);
if(height[low]<=height[high]) low++;
else high--;
}
return ret;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment