Buildings and volume of water stuck

Given buildings of width 1 and variable height, write a function returning the volume of water which remains stuck between them when it rains. This function has to be written in JavaScript.
The program will receive the list of the building heights as input array. Your program should return volume of water stuck between the buildings.
For example input: [2,1,3] result should be: 1
For example input: [3,1,2,4] result should be: 3

function result(Arr) {
    var sum = 0;
    var lArr = [];
    var rArr = [];
    var leftMax = 0;
    var tmpMax = 0;
    var rightMax = 0;
    for (Ai = 0; Ai < Arr.length; Ai++) {
      // get maximum to the right of the current element
      lArr = Arr.slice(0, Ai);
      if(lArr.length > 0) {
        tmpMax = Math.max(...lArr);
      } else {
        tmpMax = 0;
      }
      leftMax = tmpMax;
      
      // get maximum to the right of the current element
      rArr = Arr.slice(Ai+1);
      if(rArr.length > 0) {
        tmpMax = Math.max(...rArr);
      } else {
        tmpMax = 0;
      }
      rightMax = tmpMax;
      
      // get amount of water based on the left and right max elements
      if(Arr[Ai] < leftMax && Arr[Ai] < rightMax) {
        sum += Math.min(leftMax, rightMax) - Arr[Ai];
      }
    }
    return sum;
}

Leave a Reply

Your email address will not be published. Required fields are marked *