https://leetcode.com/problems/container-with-most-water/
给一个数组,数组里每个数表示一个木板的高度,任意两个木板可以构成一个容器,容积为底(两者下标之差)乘高(较短木板的长度),求给定数组中可以构成的最大容器的容积
贪心:
使用双指针遍历数组,一个指针初始在数组头部,一个指针初始在数组尾部,此时我们得到了第一个容积,即头尾木板组成的容器。
这时我们需要挪动指针,挪动哪一个指针呢?答案是挪动较短的木板的指针。
容器的容积是由短板所决定的,如果我们挪动较长指针的木板,那么得到新容器的容积只可能变得更小(底边变短,新的高只能小于等于当前高)
对于这个贪心正确性的验证,我们假设初始状态h[0]<h[n-1],此时的面积其实就已经是h[0]这个点能产生的最大面积了,因此可以舍弃掉这个点(即左指针右移),于是进入了一个新的子状态(h[1]与h[n-1])
1 class Solution { 2 public: 3 int maxArea(vector<int>& height) { 4 int size = height.size(); 5 int ans = 0; 6 7 int head = 0; 8 int tail = size-1; 9 while(head<tail){ 10 int area = min(height[head],height[tail])*(tail-head); 11 if(area>ans) ans = area; 12 if(height[head]<height[tail]) head++; 13 else tail--; 14 } 15 16 return ans; 17 } 18 };
LC11-Container With Most Water
原文:https://www.cnblogs.com/osoii/p/12971883.html