1. 题目(中等)

题目链接

每日一道leetcode:11. 盛最多水的容器_i++


每日一道leetcode:11. 盛最多水的容器_leetcode_02

2. 分析与题解

思路:双指针。面积的计算与横轴和纵轴都有关,根据木桶效应来看,纵轴中影响面积的是较短的那个纵轴。可以使用双指针,分别指向纵轴的两端。

class Solution {
public:
    int maxArea(vector<int>& height) {
        int n = height.size();
        int res = 0;
        int i = 0, j = n-1;
        while (i < j) {
            int area = min(height[i], height[j]) * (j-i);
            res = max(res, area);
            if (height[i] < height[j]) {
                i++;
            } else j --;
        }
        return res;
    }
};