Description
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.
The above vertical lines are represented by array [1,8,6,2,5,4,8,3,7]. In this case, the max area of water (blue section) the container can contain is 49.
Example
Input: [1,8,6,2,5,4,8,3,7]
Output: 49
Analyse
题目的背景是让你找到两个高度,这两个高度围起来的水缸能存储最多的水。提取题意之后,转换成公式就是让你找到(j-i)*min{a[i],a[j]}(j>i)的最大值。最最简单的方法,直接枚举所有的可能,复杂度:
O
(
n
2
)
O(n^2)
O(n2),后来发现最后一个样例n=15000,爆炸,排除。继续思考,本来想去用DP的,但仔细想想,好像这道题有着隐藏的规律,再仔细想想,发现了。
规律(推理)是这样的:从数据的两头向中间跑,哪边小就往中间走一步,然后记录最大值即可。转化成公式就是这样的:
初始i=0,j=n-1。若a[i]<a[j],则i++,否则j–,计算(j-i)*min{a[i],a[j]}(j>i),然后记录最大值。
证明:拿a[i]<a[j]为例,若a[j-1]<a[j],那么j–,无论a[j-1]比a[i]大还是小,面积都会变小,因为a[i]是短板,无论是出现更短的短板还是距离缩短,面积只会变小。若a[j-1]>a[j]道理还是一样的,所以当前这种情况是以a[i]为一端最大的面积的情况,所以就处理完了a[i],以此类推,就能解决所有的以某一个高度为一端的最大值了。
Code
class Solution {
public:
int maxArea(vector<int>& height) {
int max = 0;
int i = 0, j = height.size() - 1;
while (i < j) {
if (height[i] < height[j]) {
if (height[i] * (j - i) > max) {
max = height[i] * (j - i);
}
i++;
} else {
if (height[j] * (j - i) > max) {
max = height[j] * (j - i);
}
j--;
}
}
return max;
}
};
这道题说明,不一定所有的最优化问题需要有DP来解决,找到问题中的潜在关系才是解决问题的较优的方法。