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.
问题:
对于给定的数组a1,a2,…,an(0<=ai,0<=i<=n),求解W的最大值。
W(i,j) = min(ai,aj)*(j-i)(0 <= i < j <= n)
最直观的办法,暴力方法,两层for循环
int maxValue = 0;
for(int i = 0; i < n; ++i)
{
for(int j = i+1; j < n; ++j)
{
int dist = j - i;
int depth = (a[i] > a[j] ? a[j] : a[i]);
int tmpArea = dist * depth;
if(tmpArea > maxValue)
{
maxValue = tmpArea;
}
}
}
这个肯定解决不了问题,而且估计也违背了出题者的初衷,想想其他办法,其实影响W的只有两个因素,ai和aj的最小值,其次,i和j的距离。可以先考虑一种情况,如果存在k, j>k > i,而且ak <= ai,那么W(k,j) < W(i,j),如果ak<=aj,那么W(i,k)
int maxValue = 0;
int left = 0;
int right = n-1;
while(left < right)
{
int depth = (a[left] > a[right] ? a[right] : a[left]);
int tmpArea = (right - left) * depth;
if(tmpArea > maxValue)
{
maxValue = tmpArea;
}
if(a[left] > a[right])
{
right = right - 1;
}
else
{
left = left + 1;
}
}
至此,题目完美解决,再来看一个同类型的题目
42题,Given n non-negative integers representing an elevation map where the width of each bar is 1, compute how much water it is able to trap after raining.
(图片来源leetcode网站)
The above elevation map is represented by array [0,1,0,2,1,0,1,3,2,1,2,1]. In this case, 6 units of rain water (blue section) are being trapped. Thanks Marcos for contributing this image!
Example:
Input: [0,1,0,2,1,0,1,3,2,1,2,1]
Output: 6
思考:
给定数组a(1),a(2),…,a(n),对于k是否能蓄水,而且能储蓄多少单位的水,取决于a(k)的左边是否存在i(0< i < k)以及j(n > j > k),如果满足:
min(a(i), a(j)) > a(k)
,则k单位的桶上面可以蓄水,否则不能蓄水。
可以定义:
left(i) = max(a1, a2, ..., a(i-1))
right(i) = max(a(i+1),a(i+2),...,a(n))
则对于k(0 < k < n)的蓄水量则等于:
w(k)=max(min(left(k),right(k)) - a(k),0)
总体代码如下:
class Solution {
public:
int trap(vector<int>& height) {
size_t nSize = height.size();
if(nSize <= 2)
{
return 0;
}
int *left = new int [nSize + 1];
memset(left, 0, sizeof(int) * (nSize + 1));
int *right = new int [nSize + 1];
memset(right, 0, sizeof(int) * (nSize + 1));
for(int i = 0; i < nSize; ++i)
{
if(height[i] > left[i])
{
left[i + 1] = height[i];
}
else
{
left[i + 1] = left[i];
}
int j = nSize - i - 1;
if(height[j] > right[j + 1])
{
right[j] = height[j];
}
else
{
right[j] = right[j + 1];
}
}
int maxArea = 0;
for(int i = 0; i < nSize; ++i)
{
int depth = (left[i + 1] > right[i + 1] ? right[i + 1] : left[i + 1]);
if(height[i] < depth)
{
maxArea += depth - height[i];
}
}
if(left != NULL)
{
delete []left;
left = NULL;
}
if(right != NULL)
{
delete []right;
right = NULL;
}
return maxArea;
}
};