11. Container With Most Water

Description:

https://leetcode.com/problems/container-with-most-water/#/description

Algorithm:

squeeze from left and right. and get the maximun height of left and right.

Code:

class Solution {
public:
int maxArea(vector<int>& height) {
int left = 0;
int right = height.size() – 1;
int result = 0;

while(left < right)
{
int vol = min(height[left], height[right]) * (right – left);
result = vol > result ? vol:result;
if (height[left] < height[right])
left++;
else
right–;
}
return result;
}
};

 

Timing:

Scan once, O(n)

Leave a Reply

Your email address will not be published. Required fields are marked *