1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66

/**
* For each bar, the max rain that it could trap depends on the shorter height of left and right bars
* which is the highest bar it could reach.
*
* Travel from left to right to find the left blocking bar for each bar, then travel from right to left
* to find the bar on right side. At the end find the shorter one, and subtract the origin height
*/
int TrappingRainWater(int eMap[], int n) { if (n < 3) return 0; int limit[n]; int rain = 0; int maxHeight = 0; for (int i = 0; i < n; ++i) { if (maxHeight < eMap[i]) maxHeight = eMap[i]; limit[i] = maxHeight; } maxHeight = 0; for (int i = n-1; i >= 0; --i) { if (maxHeight < eMap[i]) maxHeight = eMap[i]; if (maxHeight < limit[i]) limit[i] = maxHeight; rain += limit[i] - eMap[i]; } return rain; } #include <stdio.h> int main(int argc, char** argv) { int a[] = {0,1,0,2,1,0,1,3,2,1,2,1}; // rain = 6; int b[] = {6,4,2,0,3,2,0,3,1,4,5,3,2,7,5,3,0,1,2,1,3,4,6,8,1,3}; // rain = 83 int sizeOfInt = sizeof(int); int rain = TrappingRainWater(a, sizeof(a)/sizeOfInt); printf("%d\n", rain); rain = TrappingRainWater(b, sizeof(b)/sizeOfInt); printf("%d\n", rain); return 0; }
View Program Text


Test Status