[InterviewBit] Rain Water Trapped

Rain Water Trapped

  • Time : O(n)
  • Space : O(1)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
int Solution::trap(const vector<int> &A) {
int l = 0, r = A.size() - 1, res = 0, mi = 0;
while(l < r) {
if(A[l] > mi and A[r] > mi) {
res += (r - l + 1) * (min(A[l],A[r]) - mi);
mi = min(A[l],A[r]);
res -= mi;
if(A[l] < A[r]) l++;
else r--;
} else if(A[l] <= mi and A[r] >= mi) {
res -= A[l++];
} else if(A[r] <= mi and A[l] >= mi) {
res -= A[r--];
}
}
return res - mi;
}

Author: Song Hayoung
Link: https://songhayoung.github.io/2022/08/30/PS/interviewbit/rain-water-trapped/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.