LeetCode in Kotlin

2713. Maximum Strictly Increasing Cells in a Matrix

Hard

Given a 1-indexed m x n integer matrix mat, you can select any cell in the matrix as your starting cell.

From the starting cell, you can move to any other cell in the same row or column, but only if the value of the destination cell is strictly greater than the value of the current cell. You can repeat this process as many times as possible, moving from cell to cell until you can no longer make any moves.

Your task is to find the maximum number of cells that you can visit in the matrix by starting from some cell.

Return an integer denoting the maximum number of cells that can be visited.

Example 1:

Input: mat = [[3,1],[3,4]]

Output: 2

Explanation: The image shows how we can visit 2 cells starting from row 1, column 2. It can be shown that we cannot visit more than 2 cells no matter where we start from, so the answer is 2.

Example 2:

Input: mat = [[1,1],[1,1]]

Output: 1

Explanation: Since the cells must be strictly increasing, we can only visit one cell in this example.

Example 3:

Input: mat = [[3,1,6],[-9,5,7]]

Output: 4

Explanation: The image above shows how we can visit 4 cells starting from row 2, column 1. It can be shown that we cannot visit more than 4 cells no matter where we start from, so the answer is 4.

Constraints:

Solution

import java.util.concurrent.atomic.AtomicInteger

class Solution {
    fun maxIncreasingCells(mat: Array<IntArray>): Int {
        val n = mat.size
        val m = mat[0].size
        val map: MutableMap<Int, MutableList<IntArray>> = HashMap()
        for (i in 0 until n) {
            for (j in 0 until m) {
                val `val` = mat[i][j]
                if (!map.containsKey(`val`)) {
                    map.put(`val`, ArrayList())
                }
                map[`val`]!!.add(intArrayOf(i, j))
            }
        }
        val memo = Array(n) { IntArray(m) }
        val res = IntArray(n + m)
        val max = AtomicInteger()
        map.keys.stream().sorted().forEach { a: Int ->
            for (pos in map[a]!!) {
                val i = pos[0]
                val j = pos[1]
                memo[i][j] = res[i].coerceAtLeast(res[n + j]) + 1
                max.set(max.get().coerceAtLeast(memo[i][j]))
            }
            for (pos in map[a]!!) {
                val i = pos[0]
                val j = pos[1]
                res[n + j] = res[n + j].coerceAtLeast(memo[i][j])
                res[i] = res[i].coerceAtLeast(memo[i][j])
            }
        }
        return max.get()
    }
}