- 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
- 60 lines of Java from the credited upstream file 3363.java.
- The implementation visibly relies on sequence storage, cached states.
- 7 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 maxCollectedFruits(int[][] fruits) {3 final int n = fruits.length;4 return getTopLeft(fruits) + getTopRight(fruits) + getBottomLeft(fruits) 5 - 2 * fruits[n - 1][n - 1];6 }7 8 private int getTopLeft(int[][] fruits) {9 final int n = fruits.length;10 int res = 0;11 for (int i = 0; i < n; ++i)12 res += fruits[i][i];13 return res;14 }15 16 private int getTopRight(int[][] fruits) {17 final int n = fruits.length;18 19 int[][] dp = new int[n][n];20 dp[0][n - 1] = fruits[0][n - 1];21 for (int x = 0; x < n; ++x)22 for (int y = 0; y < n; ++y) {23 if (x >= y && !(x == n - 1 && y == n - 1))24 continue;25 for (int[] dir : new int[][] {{1, -1}, {1, 0}, {1, 1}}) {26 final int i = x - dir[0];27 final int j = y - dir[1];28 if (i < 0 || i == n || j < 0 || j == n)29 continue;30 if (i < j && j < n - 1 - i)31 continue;32 dp[x][y] = Math.max(dp[x][y], dp[i][j] + fruits[x][y]);33 }34 }35 return dp[n - 1][n - 1];36 }37 38 private int getBottomLeft(int[][] fruits) {39 final int n = fruits.length;40 41 int[][] dp = new int[n][n];42 dp[n - 1][0] = fruits[n - 1][0];43 for (int y = 0; y < n; ++y)44 for (int x = 0; x < n; ++x) {45 if (x <= y && !(x == n - 1 && y == n - 1))46 continue;47 for (int[] dir : new int[][] {{-1, 1}, {0, 1}, {1, 1}}) {48 final int i = x - dir[0];49 final int j = y - dir[1];50 if (i < 0 || i == n || j < 0 || j == n)51 continue;52 if (j < i && i < n - 1 - j)53 continue;54 dp[x][y] = Math.max(dp[x][y], dp[i][j] + fruits[x][y]);55 }56 }57 return dp[n - 1][n - 1];58 }59}60