Difficulty: 3
Frequency: 2
Problem:
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.
Solution:
class Solution {
public:
int maxArea(vector<int> &height) {
// Start typing your C/C++ solution below
// DO NOT write int main() function
if (height.size()<2)
return 0;
int i_start = 0, i_end = height.size() - 1;
int i_area = (height[i_start]<height[i_end]?height[i_start]:height[i_end])*(i_end - i_start);
int i_temp_area = 0;
while(i_start<i_end)
{
if (height[i_start]<height[i_end])
++i_start;
else
--i_end;
i_temp_area = (height[i_start]<height[i_end]?height[i_start]:height[i_end])*(i_end - i_start);
i_area = i_area>i_temp_area?i_area:i_temp_area;
}
return i_area;
}
};
Notes:
Originally, I misunderstood this problem. This algorithm is borrowed from other.
Time complexity is O(n).
Another thing is that when (height[i_start] == height[i_end]), move either i_start or i_end is OK.