-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathproblem43.c
More file actions
64 lines (52 loc) · 1.45 KB
/
problem43.c
File metadata and controls
64 lines (52 loc) · 1.45 KB
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
#include <stdio.h>
#include <stdlib.h>
int calculateTrappedWater(int *height, int n) {
int left = 0, right = n - 1;
int leftMax = 0, rightMax = 0;
int totalWater = 0;
while (left < right) {
if (height[left] < height[right]) {
if (height[left] >= leftMax) {
leftMax = height[left];
} else {
totalWater += leftMax - height[left];
}
left++;
} else {
if (height[right] >= rightMax) {
rightMax = height[right];
} else {
totalWater += rightMax - height[right];
}
right--;
}
}
return totalWater;
}
int main() {
int n;
printf("How many buildings are there? ");
scanf("%d", &n);
if (n <= 0) {
printf("Number of buildings must be greater than zero.\n");
return 1;
}
int *heights = (int *)malloc(n * sizeof(int));
if (heights == NULL) {
printf("Failed to allocate memory.\n");
return 1;
}
printf("Enter the height of each building :\n");
for (int i = 0; i < n; i++) {
scanf("%d", &heights[i]);
if (heights[i] < 0) {
printf("!! Invalid Input !!\n");
free(heights);
return 1;
}
}
int trapped = calculateTrappedWater(heights, n);
printf("The total amount of trapped rainwater is: %d units\n", trapped);
free(heights);
return 0;
}