leetcode/src/s0011_container_with_most_w...

25 lines
940 B
C++

#include "s0011_container_with_most_water.hpp"
// 双指针:
// 一开始左指针指向数组开头,右指针指向数组结尾
// 两个指针向中间移动
// 每次移动的时候移动较小的那个指针:
// 由于储存的水量 = 两指针之间的距离 * 较小的指针的值
// 因此如果移动较大的指针,那么储存的水量一定不会超过之前的
// 也就是说只有当移动小的指针时才有可能让储存的水量超过之前的
// 因此每次迭代我们移动较小的指针,然后统计出最大的储存水量
int S0011::maxArea(vector<int>& height) {
int max{0};
for (int l{0}, r{static_cast<int>(height.size() - 1)}; r != l;) {
if (height.at(l) > height.at(r)) {
max = (r - l) * height.at(r) > max ? (r - l) * height.at(r) : max;
r--;
} else {
max = (r - l) * height.at(l) > max ? (r - l) * height.at(l) : max;
l++;
}
}
return max;
}