Mark As Completed Discussion

Maximum Water Level at columni

As explained previously in the quote, now we can get the maximum water level at index/column i pretty easily. Before that, think about the values we currently have at hand on left[] and right[] arrays.

TEXT
1left[i] = Maximum value of heights if we keep going to left from i.
2right[i] = Maximum value of heights if we keep going to right from i.

So what we need to do is get the minimum of these two to get the maximum water level at i. Remember, this is not yet what we want at each column/index. We want to have the amount of water at each column. So we subtract the height at i from the maximum level of water. That would be our desired value at each index.

1maxLevelOfWater[i] = Math.min(left[i], right[i]);
2water[i] = maxLevelOfWater[i] - height[i];

Finally, we can sum up the whole max_level_of_water array to get the final result. But do we really need another array max_level_of_water for this?

No, we don't! We can get the sum directly by calculating from left[] and right[] at each column and adding them (starting from 0) during the iteration. The modified pseudo code is below:

1let result = 0;
2for (let i = 0; i < n; i++) {
3    result += Math.min(left[i], right[i]) - height[i];
4}

To understand this, I am giving you the below diagram showing the values of an example at each step and arrays.

Final Solution

So the final solution is given below:

JAVASCRIPT
OUTPUT
:001 > Cmd/Ctrl-Enter to run, Cmd/Ctrl-/ to comment