class Solution {
public:
/**
* max water
* @param arr int整型vector the array
* @return long长整型
*/
long long maxWater(vector<int>& arr) {
// write code here
if(arr.size() < 3)
return 0;
long long res = 0;
// 设置双指针,l指向数组开头,r指向数组末尾
int l = 0, r = arr.size() - 1;
// 求出左边和右边的最大值
int l_max = 0, r_max = 0;
// 每次都计算每个索引位置上存储的水,并加起来
while(l < r) { // 当左边索引小于右边索引时
l_max = max(l_max, arr[l]);
r_max = max(r_max, arr[r]);
if(arr[l] < arr[r]) { // 如果右边的元素大于左边,则计算左边cunc
res += l_max - arr[l];
l++;
}else { // 如果右边的元素小于左边,则计算右边存储的水
res += r_max - arr[r];
r--;
}
}
return res;
}
};