11. Container With Most Water
Medium
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 and n is at least 2.
The above vertical lines are represented by array [1,8,6,2,5,4,8,3,7]. In this case, the max area of water (blue section) the container can contain is 49.
Example:
Input: [1,8,6,2,5,4,8,3,7]
Output: 49 这个题想了很久,结果没想到怎么做,其实现在理解以下就是一个双边贪心的策略,尽量的宽,又尽力的高才能存储更多的水,所以,从两端向中间贪心,如果左边的比右边的高就更新右边的边,往中间靠一阶,看能不能得到更好的,同理,如果右边的比左边的短,右边就向右扫描一个,如果相等,那随便选择一边更新一格就可以。
class Solution {
public:
int maxArea(vector<int>& height) {
int r = ; int l = height.size()-;
int Max = (min(height[l],height[r])*(l-r));
while(r<l){
if(height[r] <= height[l]) r++;
else if(height[l] < height[r]) l--;
Max = max(Max,(min(height[l],height[r])*(l-r)));
}
return Max;
}
};