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.
解法1: Two pointers, O(N) Time, One pass
比较典型的two pointers的题目. 主要思路是, 一个container的面积是(right- left) * (左右两块挡板较短的那一块的长度)
那么要maximize一个面积,可以做的是增长距离,或者是增长板的长度.
设两个指针,从左右边界开始,这个时候,我们的长度是最长的.计算一下当前的面积
如果要提高这个面积, 因为只能缩小长度,则我们必须要提高短板的长度.
那么不停的移动左右指针(哪一根指针指向的板较短就移哪一根)
C++
Java