#include <ios>
class Solution {
public:
/**
* max water
* @param arr int整型vector the array
* @return long长整型
*/
long long maxWater(vector<int>& arr) {
int n = arr.size();
int l = 0, r = n - 1;
int leftmax = arr[l], rightmax = arr[r];
int res = 0;
while (l < r) {
leftmax = max(leftmax, arr[l]);
rightmax = max(rightmax, arr[r]);
if (leftmax < rightmax) {
res += leftmax - arr[l];
++l;
} else {
res += rightmax - arr[r];
--r;
}
}
return res;
}
};
思路:双指针。
木桶原理,一个槽装的水是由其左右两边较短的柱子决定的。

京公网安备 11010502036488号