[LeetCode] Maximum Path Intersection Sum in a Grid

3938. Maximum Path Intersection Sum in a Grid

You are given an m x n integer matrix grid.

Two players move across the grid:

  • Player 1 starts at the top-left cell (0, 0) and can move only right or down. Their destination is the bottom-right cell (m - 1, n - 1).
  • Player 2 starts at the bottom-left cell (m - 1, 0) and can move only right or up. Their destination is the top-right cell (0, n - 1).

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.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42


class Solution {
int helper(vector<vector<int>>& A) {
int n = A.size(), m = A[0].size(), res = INT_MIN;
if(m != 1) res = max({res, A[0][0] + A[0][1], A[0][m-1] + A[0][m-2], A[n-1][0] + A[n-1][1], A[n-1][m-1] + A[n-1][m-2]});
if(n != 1) res = max({res, A[0][0] + A[1][0], A[0][m-1] + A[1][m-1], A[n-1][0] + A[n-2][0], A[n-1][m-1] + A[n-2][m-1]});
for(int i = 0; i < n; i++) {
vector<int> mi(m, INT_MIN);
mi[0] = 0;
for(int j = 0, pre = 0; j < m; j++) {
pre += A[i][j];
int lookup = j;
if(i == 0 or i == n - 1 or j == 0 or j == m - 1) {
lookup--;
}
if(0 <= lookup and lookup < m) res = max(res, pre - mi[lookup]);
if(j + 1 < m) mi[j+1] = min(mi[j], pre);
}
}
return res;
}
void rotate(vector<vector<int>>& grid) {
int n = grid.size(), m = grid[0].size();
vector<vector<int>> tmp(m, vector<int>(n));
for (int i = 0; i < n; ++i) {
for (int j = 0; j < m; ++j) {
tmp[j][n - 1 - i] = grid[i][j];
}
}
grid = move(tmp);
}
public:
int maxScore(vector<vector<int>>& grid) {
int res = INT_MIN;
for(int i = 0; i < 2; i++) {
res = max(res, helper(grid));
rotate(grid);
}
return res;
}
};
Author: Song Hayoung
Link: https://songhayoung.github.io/2026/09/04/PS/LeetCode/maximum-path-intersection-sum-in-a-grid/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.