Problem:
Largest Rectangle

Given a matrix (H × W) which contains only 1 and 0, find the area of the largest rectangle which only contains 0s.

Input

H W
c1,1 c1,2 ... c1,W
c2,1 c2,2 ... c2,W
:
cH,1 cH,2 ... cH,W

In the first line, two integers H and W separated by a space character are given. In the following H lines, ci,j, elements of the H × W matrix, are given.

Output

Print the area (the number of 0s) of the largest rectangle.

Constraints

1 ≤ H, W ≤ 1,400

Sample Input

4 5
0 0 1 0 0
1 0 0 0 0
0 0 0 1 0
0 0 0 1 0

Sample Output

6

Solution in Scala (judge verdict: Wrong Answer)

import scala.io.StdIn

object Main extends App {

  val Array(h, w) = StdIn.readLine().split(' ').map(_.toInt)

  val tiles = (0 until h).map(_ => StdIn.readLine().split(' ')).toArray
  val square = Array.fill[Int](h, w)(1)

  (0 until h).foreach { i =>
    (0 until w).foreach { k =>
      square(i)(k) = if (tiles(i)(k) == "1") {
        0
      } else if (i == 0) {
        square(i)(k)
      } else {
        square(i - 1)(k) + 1
      }
    }
  }

  case class Rect(height: Int, pos: Int)

  def pop(lst: List[Rect], row: Array[Int], index: Int): (List[Rect], Int) = {
    val currentH = if (index == row.length) row(index - 1) else row(index)
    lst.foldLeft((List.empty[Rect], 0)) { (acc, e) =>
      if (e.height >= currentH) {
        (acc._1, scala.math.max(acc._2, e.height * (index - e.pos)))
      } else {
        (e :: acc._1, acc._2)
      }
    }
  }

  def loop(lst: List[Rect], row: Array[Int], index: Int): Int = {
    if (index == row.length) {
      pop(lst, row, index)._2
    } else if (lst.isEmpty || lst(0).height < row(index)) {
      loop(Rect(row(index), index) :: lst, row, index + 1)
    } else if (lst(0).height == row(index)) {
      loop(lst, row, index + 1)
    } else {
      val r = pop(lst, row, index)
      if (r._1.isEmpty) {
        r._2
      }
      else {
        loop(r._1, row, index + 1)
      }
    }
  }

  val result = square.foldLeft(0L) { (acc, elm) =>
    scala.math.max(acc, loop(List.empty[Rect], elm, 0))
  }

  println(result)
}