forked from HarshCasper/NeoAlgo
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathTrapping_rain_water.c
88 lines (74 loc) · 1.57 KB
/
Trapping_rain_water.c
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
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
/* Given n non-negative integers representing an elevation map where the
width of each bar is 1, compute how much water it can trap after raining. */
#include<stdio.h>
#include<stdlib.h>
#include<math.h>
int trap(int * arr, int n);
int main() {
int n, m;
// accepting the sizes
printf("Enter size of array: ");
scanf("%d", & n);
int * arr = (int *) malloc(sizeof(int) * n);
// accepting the array elements
printf("Enter the elements: ");
for (int i = 0; i < n; i++) {
scanf("%d ", arr + i);
}
// print the trapped water value
printf("Water trapped is %d",
trap(arr, n));
return 0;
}
// function to find the water trapped
int trap(int * arr, int n){
int Sum = 0, water = 0, top = 0;
for(int i = 0; i < n; i++)
{
// Collect the higher bars //
if(top < arr[i])
{
water += Sum;
top = arr[i];
Sum = 0;
}
else
Sum += top - arr[i];
}
// resetting the values to zero
top=0, Sum=0;
for(int i = n - 1; i > -1; i--)
{
// collect both the equal and higher bar
if(top <= arr[i])
{
water += Sum;
top = arr[i];
Sum = 0;
}
else
Sum += top - arr[i];
}
// return the answer
return water;
}
/*
Time Complexity: O(n)
Space Complexity: O(n)
Example 1:
Input:
Enter size of array:
12
Enter the elements:
0 1 0 2 1 0 1 3 2 1 2 1
Output:
Water trapped is: 6
Example 2:
Input:
Enter size of array:
5
Enter the elements:
1 4 2 0 1
Output:
Water trapped is: 1
*/