#2684

Maximum Number of Moves in a Grid

Medium
ArrayDynamic ProgrammingMatrixDynamic ProgrammingMatrix Traversal
LeetCode ↗

Approaches

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

Intuition

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

In the optimal approach, we use dynamic programming to store the maximum moves possible from each cell. This avoids redundant calculations and allows us to build solutions incrementally.

⚙️

Algorithm

3 steps
  1. 1Step 1: Create a DP table where dp[i][j] represents the maximum moves from cell (i, j).
  2. 2Step 2: Initialize the first column of the DP table to 0 since no moves can be made from the first column.
  3. 3Step 3: Iterate through the grid from left to right, updating the DP table based on valid moves from the previous column.
solution.py9 lines
1def maxMoves(grid):
2    m, n = len(grid), len(grid[0])
3    dp = [[0] * n for _ in range(m)]
4    for j in range(1, n):
5        for i in range(m):
6            for r in [i-1, i, i+1]:
7                if 0 <= r < m and grid[r][j] > grid[i][j-1]:
8                    dp[i][j] = max(dp[i][j], dp[r][j-1] + 1)
9    return max(dp[i][-1] for i in range(m))

Complexity note: The time complexity is O(m * n) because we iterate through each cell in the grid and check up to 3 possible previous cells for each move. The space complexity is also O(m * n) due to the DP table.

  • 1Dynamic programming can significantly reduce the time complexity by avoiding redundant calculations.
  • 2Understanding the movement constraints helps in designing the DP state transitions.

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