Num 11 盛最多水的容器
- 如果要比上一个状态大,一定要宽度更大或者高度更高满足至少一个
- 从两个边界向里面走,从宽度最大开始
- 那么如果要更新出更大的面积,一定是有更高的高度,因此每次要动小边向里,找更高的高度(因为min(height[left],height[right])动大边是没用的)
- 可以验证在实际过程中不存在忽略掉最大边的可能
(实际操作中唯一一下子想不明白认为可能出问题的地方是。l2和r2小于最终l3和r3,有无可能是他们在前面受限于小边,但是实际大于l3r3围成的边)
验证过程:
- s3=min(h[l3],h[r3])*(r3-l3)
- min(h[l3],h[r3])*(r3-l3))>min(h[l2],[r3])*(r3-l2) (这个式子状态是l2<r3)
- min(h[l2],[r3])*(r3-l2)>min(h[l2],h[r2])*(r2-l2)
- 使用字母更准确一些,原理大致一样,只要保证每次动的都是小边就不会漏掉最优解
class Solution { public: int maxArea(vector<int>& height) { int sum=height.size(); int left=0; int right=sum-1; int s=min(height[left],height[right])*(right-left); while(left<right) { if(height[left]<=height[right]) { left++; if(min(height[left],height[right])*(right-left)>s) { s=min(height[left],height[right])*(right-left); } } else { right--; if(min(height[left],height[right])*(right-left)>s) { s=min(height[left],height[right])*(right-left); } } } return s; } };