- 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
- 45 lines of Python from the credited upstream file 3363.py.
- The implementation visibly relies on sequence storage, cached states.
- No explicit 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 def maxCollectedFruits(self, fruits: list[list[int]]) -> int:3 n = len(fruits)4 5 def getTopLeft() -> int:6 return sum(fruits[i][i] for i in range(n))7 8 def getTopRight() -> int:9 10 dp = [[0] * n for _ in range(n)]11 dp[0][-1] = fruits[0][-1]12 for x in range(n):13 for y in range(n):14 if x >= y and (x, y) != (n - 1, n - 1):15 continue16 for dx, dy in [(1, -1), (1, 0), (1, 1)]:17 i = x - dx18 j = y - dy19 if i < 0 or i == n or j < 0 or j == n:20 continue21 if i < j < n - 1 - i:22 continue23 dp[x][y] = max(dp[x][y], dp[i][j] + fruits[x][y])24 return dp[-1][-1]25 26 def getBottomLeft() -> int:27 28 dp = [[0] * n for _ in range(n)]29 dp[-1][0] = fruits[-1][0]30 for y in range(n):31 for x in range(n):32 if x <= y and (x, y) != (n - 1, n - 1):33 continue34 for dx, dy in [(-1, 1), (0, 1), (1, 1)]:35 i = x - dx36 j = y - dy37 if i < 0 or i == n or j < 0 or j == n:38 continue39 if j < i < n - 1 - j:40 continue41 dp[x][y] = max(dp[x][y], dp[i][j] + fruits[x][y])42 return dp[-1][-1]43 44 return getTopLeft() + getTopRight() + getBottomLeft() - 2 * fruits[-1][-1]45