Problem Description
Given an m x n grid of positive integers, you can start at any cell in the first column and move to the next column using one of three possible moves: top-right, right, or bottom-right. However, you may only move if the value in the destination cell is strictly greater than the value in the current cell. The goal is to determine the maximum number of moves you can perform.
Key Insights
- Use dynamic programming to track the maximum moves possible from each cell.
- Process the grid from rightmost column to leftmost column.
- For each cell, the move is valid only if the target cell's value is greater than the current cell’s value.
- The answer is the maximum value computed for cells in the first column.
Space and Time Complexity
Time Complexity: O(m * n) where m is the number of rows and n is the number of columns. Space Complexity: O(m * n) for the dp table.
Solution
We use dynamic programming by creating a 2D dp array where dp[i][j] represents the maximum number of moves possible starting from the cell at (i, j). We initialize the last column with 0 because no moves can be made from there. Then, for each cell from the second last column to the first column, we check its three potential next moves (top-right, right, and bottom-right) provided the value in the next cell is strictly greater. We update dp[i][j] as 1 plus the maximum dp value of the chosen move. Finally, we return the maximum value among all dp[i][0] (cells at the first column).