Problem Description
Given an m x n grid where each cell contains a coin value (which could be positive or negative), a robot starts at the top‑left cell (0, 0) and can only move right or down to reach the bottom‑right cell (m‑1, n‑1). If a cell has a non-negative number, the robot gains that many coins. If the cell is negative, it represents a robber that steals the absolute value of the coins. The robot is allowed to neutralize robbers in at most 2 cells along its path. The goal is to determine the maximum profit (total coins gained, which can be negative) the robot can achieve while traversing a valid path.
Key Insights
- Use dynamic programming because movements are restricted (only right and down) and optimal substructure exists.
- Keep track of the count of neutralizations used. Use a 3-dimensional DP state: dp[i][j][k] where (i, j) is the cell and k is the number of neutralizations used (0, 1, or 2).
- Update the DP from the top-left cell towards the bottom-right cell considering both options at a cell with a negative coin value: taking the negative value or using a neutralization (if available) to avoid loss.
- The final answer will be the maximum profit at the bottom-right cell using up to 2 neutralizations.
Space and Time Complexity
Time Complexity: O(m * n * 3) = O(m * n)
Space Complexity: O(m * n * 3) = O(m * n)
Solution
We solve the problem using dynamic programming with three dimensions to track:
- The current cell (i, j) in the grid.
- The count of neutralizations used so far (0 to 2).
For every cell, we consider two possible moves: right and down. When processing a cell:
- If the cell has a non-negative value, we simply add it to the current profit.
- If the cell has a negative value (indicating a robber), we have two choices: a. Do not use a neutralization and add the negative value. b. If we haven’t used up 2 neutralizations, use one and add 0 for that cell.
The dp state is updated accordingly from the top-left to bottom-right cell, and the maximum value at the destination using any count of neutralizations (0, 1, or 2) is returned.