LeetCode in Kotlin

3938. Maximum Path Intersection Sum in a Grid

Medium

You are given an m x n integer matrix grid.

Two players move across the grid:

Each player must choose a valid path from their respective starting cell to their destination.

A cell is called shared if it belongs to both chosen paths.

Return an integer denoting the maximum possible sum of values of all shared cells.

Example 1:

Input: grid = [[1,2,0,-3],[1,-2,1,0],[-4,2,-1,3],[3,-3,3,-2],[-1,-5,0,1]]

Output: 4

Explanation:

The diagram shows one optimal choice of paths.

Example 2:

Input: grid = [[4,-2,-3],[-1,-3,-1],[-4,2,-1]]

Output: 3

Explanation:

One optimal pair of paths is shown in the diagram.

Constraints:

Solution

import kotlin.math.max

class Solution {
    fun maxScore(grid: Array<IntArray>): Int {
        var ans = Int.MIN_VALUE
        val m = grid.size
        val n = grid[0].size
        // 1. Check all strictly interior single cells
        for (i in 1..<m - 1) {
            for (j in 1..<n - 1) {
                ans = max(ans, grid[i][j])
            }
        }
        // 2. Modified Kadane's for Rows (Minimum length 2)
        for (ints in grid) {
            var currentSum = ints[0]
            for (j in 1..<n) {
                ans = max(ans, currentSum + ints[j])
                currentSum = max(ints[j], currentSum + ints[j])
            }
        }
        // 3. Modified Kadane's for Columns (Minimum length 2)
        for (j in 0..<n) {
            var currentSum = grid[0][j]
            for (i in 1..<m) {
                ans = max(ans, currentSum + grid[i][j])
                currentSum = max(grid[i][j], currentSum + grid[i][j])
            }
        }
        return ans
    }
}