11. Container With Most Water

来源:互联网 发布:知乎雪花釉餐具安全吗 编辑:程序博客网 时间:2024/06/07 11:25

Question:Given n non-negative integers a1a2, ..., an, where each represents a point at coordinate (iai). n vertical lines are drawn such that the two endpoints of line i is at (iai) 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.

Answer:

public class Solution {    public int maxArea(int[] height) {        int maxarea = 0, l = 0, r = height.length - 1;        while (l < r) {            maxarea = Math.max(maxarea, Math.min(height[l], height[r]) * (r - l));            if (height[l] < height[r])                l++;            else                r--;        }        return maxarea;    }}

问题的关键在两边加减以后能不能保证被忽略的容量会不会更大

Here is a simple proof for the solution.
Use v[low, high] indicates the volume of container with low and high. suppose height[low] < height[high], then we move low to low+1, that means we ignored v[low, high-1],v[low, high-2],etc, if this is safe, then the algorithm is right, and it's obvious that v[low, high-1],high[low, high-2]...... can't be larger than v[low, high] since its width can't be larger than high-low, and its height is limited by height[low].