ugly mutable scala solution to avoid MLE
\nobject Solution {\n  val arr = Array.fill(1001,1001)(0)\n  def maxScore(grid: List[List[Int]]): Int =\n    var i: Int = 0; var j: Int = 0\n    arr(0)(0) = gri
```\nobject Solution {\n  val arr = Array.fill(1001,1001)(0)\n  def maxScore(grid: List[List[Int]]): Int =\n    var i: Int = 0; var j: Int = 0\n    arr(0)(0) = grid(0)(0)\n    var ans = Int.MinValue\n    i = 1; while (i<grid.length) {\n      arr(i)(0) = arr(i-1)(0) min grid(i)(0); ans = ans max (grid(i)(0) - arr(i-1)(0)); i+=1\n    }\n    j = 1; while (j<grid.head.length) {\n      arr(0)(j) = arr(0)(j-1) min grid(0)(j); ans = ans max (grid(0)(j) - arr(0)(j-1)); j+=1\n    }\n    i=1; while (i<grid.length) {\n      j=1; while (j<grid.head.length) {\n        arr(i)(j) = arr(i-1)(j) min arr(i)(j-1) min grid(i)(j)\n        ans = ans max (grid(i)(j) - (arr(i-1)(j) min arr(i)(j-1)))\n        j+=1\n      }\n      i+=1\n    }\n    ans\n\n  def maxScore1(grid: List[List[Int]]): Int =\n    val x1 = grid.map(_.scanLeft(Int.MaxValue)(_ min _).drop(1)).transpose\n      .map(_.scanLeft(Int.MaxValue)(_ min _).drop(1)).transpose\n    def getX1(i: Int)(j: Int):Option[Int] = \n      Option.when(i>=0 && i<grid.length && j>=0 && j<grid.head.length) {x1(i)(j)}\n    val x2 = (grid.toList.flatten zip x1.toList.flatten).map{case (a,b) => a-b}.max\n    val x3 = (for{i <- grid.indices; j <-grid.head.indices} yield { (i,j)})\n      .flatMap{case (i,j) =>\n        List(getX1(i-1)(j), getX1(i)(j-1)).flatten.map{case v => grid(i)(j) - v}\n      }.max\n    x3\n}\n```
['Matrix', 'Scala']