题目描述
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.
Example
Input: [1,8,6,2,5,4,8,3,7]
Output: 49
题目大意
在给出的一串数列中,寻找出两个数,它们所构成的“容器”的容量(最小高度*间距)最大。
思路分析
经典的动态规划,设置两个指针,一个从头开始遍历,一个从尾部开始遍历,直到两者相遇;要找到“容量”最大,由短板效应想到,就是要淘汰掉“短板”,就是说比较小的那一端向后(前)遍历;这样就保证了“短板”被淘汰。时间复杂度为O(n),空间复杂度为O(1)。
关键代码
int maxArea(vector<int>& height) {
int result = 0;
int n = height.size();
int p = 0, q = n-1;
while (p < q) {
int minpq = (height[p] < height[q]) ? height[p] : height[q];
int tempArea = minpq*(q-p);
if (height[q] > height[p]) { // 淘汰短板
p++;
} else {
q--;
}
result = (tempArea > result) ? tempArea : result;
}
return result;
}
总结
这是一道经典的动态规划题,这里动态规划的子问题显然是“向前还是向后遍历可以使得容量更大”,也就是说该淘汰哪一块板;再从这些子问题中找出最优解。
而根据题目所描述的,可以想到选择这两块板的初始位置,从而解决该问题。