Skip to content

Commit 5dc95bf

Browse files
committed
4
1 parent d9bfc42 commit 5dc95bf

File tree

1 file changed

+33
-1
lines changed

1 file changed

+33
-1
lines changed

TrappingRainWater/TrappingRainWater.cpp

+33-1
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,4 @@
1+
// O(n) time, O(n) space
12
class Solution {
23
public:
34
int trap(int A[], int n) {
@@ -23,4 +24,35 @@ class Solution {
2324
}
2425
return water;
2526
}
26-
};
27+
};
28+
29+
// O(n) time, O(1) space
30+
class Solution {
31+
public:
32+
int trap(int A[], int n) {
33+
int maxh = 0;
34+
int water = 0;
35+
int temp = 0;
36+
for (int i = 0; i < n; i++) {
37+
if (A[i] <= maxh) {
38+
temp += maxh - A[i];
39+
} else {
40+
maxh = A[i];
41+
water += temp;
42+
temp = 0;
43+
}
44+
}
45+
maxh = 0;
46+
temp = 0;
47+
for (int i = n - 1; i >= 0; i--) {
48+
if (A[i] < maxh) {
49+
temp += maxh - A[i];
50+
} else {
51+
maxh = A[i];
52+
water += temp;
53+
temp = 0;
54+
}
55+
}
56+
return water;
57+
}
58+
};

0 commit comments

Comments
 (0)