leetcode-11 容器裝水最多
阿新 • • 發佈:2018-12-18
測試用例:
Input: [1,8,6,2,5,4,8,3,7]
Output: 49
int maxArea(vector<int>& height) { int maxWater = 0; int i = 0, j = height.size() - 1; while (i < j) { int m=min(height[i], height[j]); maxWater = max(maxWater,(j - i)*m); while (height[i] <= m&&i<j) { i++; }//一定要強調i<j不然的話會溢位 while (height[j] <= m&&i<j) { j--; } } return maxWater; }
解釋:Start by evaluating the widest container, using the first and the last line. All other possible containers are less wide, so to hold more water, they need to be higher. Thus, after evaluating that widest container, skip lines at both ends that don't support a higher height. Then evaluate that new container we arrived at. Repeat until there are no more possible containers left.