Water collected between towers

后端 未结 26 1093
无人共我
无人共我 2020-12-22 16:51

I recently came across an interview question asked by Amazon and I am not able to find an optimized algorithm to solve this question:

You are given an input array wh

26条回答
  •  独厮守ぢ
    2020-12-22 17:26

    Here's my attempt in jQuery. It only scans to the right.

    Working fiddle (with helpful logging)

    var a = [1, 5, 3, 7, 2];
    var water = 0;
    
    $.each(a, function (key, i) {
      if (i > a[key + 1]) { //if next tower to right is bigger
          for (j = 1; j <= a.length - key; j++) { //number of remaining towers to the right
              if (a[key+1 + j] >= i) { //if any tower to the right is bigger
                  for (k = 1; k < 1+j; k++) {
                  //add to water: the difference of the first tower and each tower between the first tower and its bigger tower
                      water += a[key] - a[key+k];
                  }
              }
          }
      }
    });
    
    console.log("Water: "+water);
    

提交回复
热议问题