#2713

Maximum Strictly Increasing Cells in a Matrix

Hard
ArrayHash TableBinary SearchDynamic ProgrammingMemoizationSortingMatrixOrdered SetDynamic ProgrammingSortingGraph Traversal
LeetCode ↗

Approaches

Brute ForceOptimal
Complexity Comparison
Brute ForceOptimal Solution
Time
O(n²)
O(m * n log(m * n))
Space
O(1)
O(m * n)
💡

Intuition

Time O(m * n log(m * n))Space O(m * n)

The optimal solution sorts the cells by their values and processes them in increasing order. This allows us to efficiently calculate the maximum path length using dynamic programming, leveraging previously computed results.

⚙️

Algorithm

3 steps
  1. 1Step 1: Create a list of all cells with their values and coordinates, then sort this list by values.
  2. 2Step 2: Initialize a DP array to store the maximum path length ending at each cell.
  3. 3Step 3: Iterate through the sorted list, and for each cell, check all cells that can be reached (those with greater values) and update the DP array accordingly.
solution.py20 lines
1# Full working Python code
2from typing import List
3
4def maxIncreasingCells(mat: List[List[int]]) -> int:
5    m, n = len(mat), len(mat[0])
6    cells = [(mat[i][j], i, j) for i in range(m) for j in range(n)]
7    cells.sort()
8    dp = [[1] * n for _ in range(m)]
9    max_count = 1
10
11    for value, x, y in cells:
12        for i in range(m):
13            if mat[i][y] > value:
14                dp[i][y] = max(dp[i][y], dp[x][y] + 1)
15        for j in range(n):
16            if mat[x][j] > value:
17                dp[x][j] = max(dp[x][j], dp[x][y] + 1)
18        max_count = max(max_count, dp[x][y])
19
20    return max_count

Complexity note: The time complexity is dominated by the sorting step, which is O(m * n log(m * n)), while the space complexity is O(m * n) due to the DP array.

  • 1Sorting the cells allows us to efficiently compute paths based on previously computed results.
  • 2Dynamic programming helps to store intermediate results, avoiding redundant calculations.

Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.