11. Container With Most Water
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.
解题思路:
每次比较两边的高度,移动较低的一边,在每次移动之后都求出当前围起来的面积,并尝试更新最大值。可以想像一下
1、如果移动高度较高的一边,如果前一个高度更高,那么宽度减小了,计算面积的高度不变,整个面积变小了,如果前一个高度比较低的一边还要低,那整个高度都变小了,宽度也变小了,总体面积变小。
2、当固定高度较低的一边时,移动高度较高的一边,那么整个形状的宽度减小,高度不变,因而整个面积减小。
class Solution { public: int maxArea(vector<int>& height) { int low=0,high=height.size()-1; int res=0; while(low<=high){ res=max(res,min(height[low],height[high])*(high-low)); if(height[low]<height[high]){ low++; } else { high--; } } return res; } };