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
这个题想了很久,结果没想到怎么做,其实现在理解以下就是一个双边贪心的策略,尽量的宽,又尽力的高才能存储更多的水,所以,从两端向中间贪心,如果左边的比右边的高就更新右边的边,往中间靠一阶,看能不能得到更好的,同理,如果右边的比左边的短,右边就向右扫描一个,如果相等,那随便选择一边更新一格就可以。
1 class Solution { 2 public: 3 int maxArea(vector<int>& height) { 4 int r = 0; int l = height.size()-1; 5 int Max = (min(height[l],height[r])*(l-r)); 6 while(r<l){ 7 if(height[r] <= height[l]) r++; 8 else if(height[l] < height[r]) l--; 9 Max = max(Max,(min(height[l],height[r])*(l-r))); 10 } 11 return Max; 12 } 13 };