Water collected between towers

后端 未结 26 998
无人共我
无人共我 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:15

    Here is one more solution written on Scala

    def find(a: Array[Int]): Int = {
      var count, left, right = 0
    
      while (left < a.length - 1) {
        right = a.length - 1
        for (j <- a.length - 1 until left by -1) {
          if (a(j) > a(right)) right = j
        }
    
        if (right - left > 1) {
          for (k <- left + 1 until right) count += math.min(a(left), a(right)) - a(k)
          left = right
        } else left += 1
      }
    
      count
    }
    

提交回复
热议问题