I have a homework problem in C++ that I could (and did) solve, but not fast enough.
So the problem goes like this: On a platform, there are n bars of equal width and height. It starts raining. Find out the quantity of water that fits in between the bars (Very bad enunciation , I know, it's better to look at the example). Examples:
n = 6
bar lengths = {3, 0, 0, 2, 0, 4}
Answer would be = 10
The cubes of water would "fill out" the empty space between the bars and I need the find the number of cubes:
Explanation:

Another example:
n = 12
bar lengths = {0, 1, 0, 2, 1, 0, 1, 3, 2, 1, 2, 1}
Answer = 6
What I tried:
For each spot in the array, I found the maximum height bar to the left of it and to the right of it and then I "filled" this spot with the minimum between the maximum to the left and the maximum to the right minus the height of the bar at the present spot:
#include <iostream>
using namespace std;
int main() {
int n, a[100001], i, j, volume=0, max_left, max_right;
cin >> n;
// Input the array
for (i=0; i<n; i++) {
cin >> a[i];
}
// For each element (except the first and last)
for (i=1; i<(n-1); i++) {
max_left = max_right = a[i];
// Find the maximum to the left of it and to the right of it
for (j=0; j<i; j++) {
if (a[j] > max_left) {
max_left = a[j];
}
}
for (j=(i+1); j<n; j++) {
if (a[j] > max_right) {
max_right = a[j];
}
}
// The quantity of water that fits on this spot is equal to
// the minimum between the maxes, minus the height of the
// bar in this spot
volume += (min(max_left, max_right) - a[i]);
}
cout << volume;
return 0;
}
The solution is good, I get the corrent results. But the speed is a problem. I believe the complexity of this solution is O(n^2), if I'm not mistaken. Now the problem has to be solved in O(n). The problem is: How can I find the maxes in both directions for each element in O(n)? Any help will be appreciated. Thanks!