[AlgoExpert] Water Area

Water Area

  • Time : O(n)
  • Space : O(1)
1
2
3
4
5
6
7
8
9
10
11
12
13
int waterArea(vector<int> h) {
int res = 0, l = 0, r = h.size() - 1, mi = 0;
while(l < r) {
while(l <= r and mi >= h[l]) l++;
while(l <= r and mi >= h[r]) r--;
if(l <= r) {
res += (min(h[l], h[r]) - mi) * (r - l + 1);
mi = min(h[l], h[r]);
}
}

return res - accumulate(begin(h), end(h), 0);
}
Author: Song Hayoung
Link: https://songhayoung.github.io/2022/05/10/PS/AlgoExpert/water-area/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.