-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathDay7.cpp
More file actions
36 lines (35 loc) · 925 Bytes
/
Copy pathDay7.cpp
File metadata and controls
36 lines (35 loc) · 925 Bytes
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
#include<iostream>
using namespace std;
int main() {
int n;
cout << "Enter the number of bars: ";
cin >> n;
int height[200001];
cout << "Enter the heights of the bars: ";
for(int i = 0; i < n; i++) {
cin >> height[i];
}
if(n < 3) {
cout << "Water trapped: 0" << endl;
return 0;
}
int left = 0, right = n - 1;
int leftMax = 0, rightMax = 0, water = 0;
while(left < right) {
if(height[left] < height[right]) {
if(height[left] >= leftMax)
leftMax = height[left];
else
water += leftMax - height[left];
left++;
} else {
if(height[right] >= rightMax)
rightMax = height[right];
else
water += rightMax - height[right];
right--;
}
}
cout << "Water trapped: " << water << endl;
return 0;
}