LeetCode-in-Java

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

public class Solution {
    public int maxScore(int[][] grid) {
        int ans = Integer.MIN_VALUE;
        int m = grid.length;
        int n = grid[0].length;
        // 1. Check all strictly interior single cells
        for (int i = 1; i < m - 1; i++) {
            for (int j = 1; j < n - 1; j++) {
                ans = Math.max(ans, grid[i][j]);
            }
        }
        // 2. Modified Kadane's for Rows (Minimum length 2)
        for (int[] ints : grid) {
            int currentSum = ints[0];
            for (int j = 1; j < n; j++) {
                ans = Math.max(ans, currentSum + ints[j]);
                currentSum = Math.max(ints[j], currentSum + ints[j]);
            }
        }
        // 3. Modified Kadane's for Columns (Minimum length 2)
        for (int j = 0; j < n; j++) {
            int currentSum = grid[0][j];
            for (int i = 1; i < m; i++) {
                ans = Math.max(ans, currentSum + grid[i][j]);
                currentSum = Math.max(grid[i][j], currentSum + grid[i][j]);
            }
        }
        return ans;
    }
}