We read every piece of feedback, and take your input very seriously.
To see all available qualifiers, see our documentation.
1 parent d9bfc42 commit 5dc95bfCopy full SHA for 5dc95bf
TrappingRainWater/TrappingRainWater.cpp
@@ -1,3 +1,4 @@
1
+// O(n) time, O(n) space
2
class Solution {
3
public:
4
int trap(int A[], int n) {
@@ -23,4 +24,35 @@ class Solution {
23
24
}
25
return water;
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
47
+ for (int i = n - 1; i >= 0; i--) {
48
+ if (A[i] < maxh) {
49
50
51
52
53
54
55
56
+ return water;
57
58
0 commit comments