给你 n 个非负整数 a1,a2,…,an,每个数代表坐标中的一个点 (i, ai) 。在坐标内画 n 条垂直线,垂直线 i 的两个端点分别为 (i, ai) 和 (i, 0)。找出其中的两条线,使得它们与 x 轴共同构成的容器可以容纳最多的水。
    说明:你不能倾斜容器,且 n 的值至少为 2。
    11. 盛最多水的容器 - 图1
    法一:最优的双指针
    比较好理解的思路,左右两边的柱子往中间靠,保留最大值。
    时间复杂度:O(N),双指针总计最多遍历整个数组一次。
    空间复杂度:O(1),只需要额外的常数级别的空间

    1. class Solution {
    2. public int maxArea(int[] height) {
    3. int left = 0;
    4. int right = height.length-1;
    5. int res = 0;
    6. while (left < right) {
    7. int area = (right - left) * Math.min(height[left], height[right]);
    8. res = Math.max(res, area);
    9. if (height[left] < height[right]) {
    10. left++;
    11. } else {
    12. right--;
    13. }
    14. }
    15. return res;
    16. }
    17. }

    11. 盛最多水的容器 - 图2
    法二:不推荐暴力法
    时间复杂度:o(n平方)

    1. // 暴力法,不推荐
    2. class Solution {
    3. public int maxArea(int[] height) {
    4. int area = 0;
    5. int max = 0;
    6. for (int i=0; i<height.length-1; i++) {
    7. for (int j=i+1; j<height.length; j++) {
    8. area = (j - i) * Math.min(height[i], height[j]);
    9. if (area > max) {
    10. max = area;
    11. }
    12. }
    13. }
    14. return max;
    15. }
    16. }

    11. 盛最多水的容器 - 图3