Path With Maximum Minimum Value Problem
Description
LeetCode Problem 1102.
Given an m x n integer matrix grid, return the maximum score of a path starting at (0, 0) and ending at (m - 1, n - 1) moving in the 4 cardinal directions.
The score of a path is the minimum value in that path.
- For example, the score of the path
8 → 4 → 5 → 9is4.
Example 1:

Input: grid = [[5,4,5],[1,2,6],[7,4,6]]
Output: 4
Explanation: The path with the maximum score is highlighted in yellow.
Example 2:

Input: grid = [[2,2,1,2,2,2],[1,2,2,2,1,2]]
Output: 2
Example 3:

Input: grid = [[3,4,6,3,4],[0,2,1,1,7],[8,8,3,2,7],[3,2,4,9,8],[4,1,2,0,0],[4,6,5,4,3]]
Output: 3
Constraints:
m == grid.lengthn == grid[i].length1 <= m, n <= 1000 <= grid[i][j] <= 10^9
Solution
Approach: Open Cells from Largest to Smallest + Union-Find
Think of it the other way around: for a threshold t, can we walk from the start to the end using only cells with value >= t? The answer is the largest t for which we can.
Picture the grid as flooded, and "open" the cells one by one from the largest value down. Every time a cell opens, join it with each of its open neighbors in a union-find structure. Right after opening a cell of value v, the open cells are exactly the cells >= v (ties aside), so the start and the end are in the same group exactly when a path with score >= v exists.
So the first time (0, 0) and (m - 1, n - 1) end up in the same group, the value of the cell we just opened is the answer:
- A path with score
vexists: it uses only open cells, all>= v. - No path with a higher score exists, otherwise start and end would have been joined before this cell was opened.
Both endpoints are part of every path, so they must be open too. That is checked along the way, and it also covers the 1×1 grid, where the answer is the single cell.
Complexity: O(mn log(mn)) time for sorting the cells (the union-find steps are almost O(1) each), and O(mn) extra space.
class Solution:
def maximumMinimumPath(self, grid: List[List[int]]) -> int:
m, n = len(grid), len(grid[0])
parent = list(range(m * n))
def find(x: int) -> int:
while parent[x] != x:
parent[x] = parent[parent[x]] # path halving
x = parent[x]
return x
# Open the cells from the largest value down, joining each one to its open neighbors.
cells = sorted(((grid[i][j], i, j) for i in range(m) for j in range(n)), reverse=True)
opened = [[False] * n for _ in range(m)]
for value, i, j in cells:
opened[i][j] = True
for x, y in ((i - 1, j), (i + 1, j), (i, j - 1), (i, j + 1)):
if 0 <= x < m and 0 <= y < n and opened[x][y]:
parent[find(x * n + y)] = find(i * n + j)
# Start and end are joined only through cells >= value, and this cell is needed.
if opened[0][0] and opened[m - 1][n - 1] and find(0) == find(m * n - 1):
return value
return -1 # not reached: once every cell is open, start and end are joined