• + 0 comments

    scala:

    import scala.collection.mutable.Stack
    import scala.io.StdIn.readLine
    
    object Solution {
      private def carve(heights: Seq[Int]): Int = {
        val extendedHeights = heights :+ 0
        val stack = Stack[Int]()
        var maxArea = 0
        for (i <- extendedHeights.indices) {
          while (stack.nonEmpty && extendedHeights(i) < extendedHeights(stack.top)) {
            val height = extendedHeights(stack.pop())
            val width = if (stack.isEmpty) i else (i - stack.top - 1)
            maxArea = math.max(maxArea, height * width)
          }
          stack.push(i)
        }
        maxArea
      }
    
      def main(args: Array[String]): Unit = {
        readLine()
        val heights = readLine().trim.split(' ').map(_.toInt).toSeq
        println(carve(heights))
      }
    }