- Define precisely what one DP state represents.
- Establish the base cases before transitions are evaluated.
- Process states in dependency order and combine only already-known values.
Code notes
- 44 lines of Java from the credited upstream file 361.java.
- The implementation visibly relies on sequence storage, cached states.
- 6 loop blocks detected.
Complexity
Multiply the number of reachable states by the work performed for each transition, then include the stored state table in memory usage.
Check the problem constraints before deciding whether this complexity will pass.
Use this to learn the idea, then write your own version.
1class Solution {2 public int maxKilledEnemies(char[][] grid) {3 if (grid.length == 0 || grid[0].length == 0)4 return 0;5 6 final int m = grid.length;7 final int n = grid[0].length;8 9 int[][] dp = new int[m][n];10 11 12 for (int i = 0; i < m; ++i) {13 enemyCount = 0;14 for (int j = 0; j < n; ++j)15 update(grid, i, j, dp);16 enemyCount = 0;17 for (int j = n - 1; j >= 0; --j)18 update(grid, i, j, dp);19 }20 21 for (int j = 0; j < n; ++j) {22 enemyCount = 0;23 for (int i = 0; i < m; ++i)24 update(grid, i, j, dp);25 enemyCount = 0;26 for (int i = m - 1; i >= 0; --i)27 update(grid, i, j, dp);28 }29 30 return Arrays.stream(dp).flatMapToInt(Arrays::stream).max().getAsInt();31 }32 33 private int enemyCount = 0;34 35 private void update(char[][] grid, int i, int j, int[][] dp) {36 if (grid[i][j] == '0')37 dp[i][j] += enemyCount;38 else if (grid[i][j] == 'E')39 ++enemyCount;40 else 41 enemyCount = 0;42 }43}44