- 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
- 36 lines of Python from the credited upstream file maximum-walls-destroyed-by-robots.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.
123 45class Solution(object):6 def maxWalls(self, robots, distance, walls):7 """8 :type robots: List[int]9 :type distance: List[int]10 :type walls: List[int]11 :rtype: int12 """13 x_d = [(0, 0)]+sorted(zip(robots, distance), key=lambda x: x[0])+[(float("inf"), 0)]14 walls.sort()15 left0 = left1 = right = curr = 016 dp, new_dp = [0]*2, [0]*217 for i in xrange(1, len(x_d)-1):18 while curr < len(walls) and walls[curr] < x_d[i][0]:19 curr += 120 r = min(x_d[i][0]+x_d[i][1], x_d[i+1][0]-1)21 while right < len(walls) and walls[right] <= r:22 right += 123 new_dp[1] = max(dp[0], dp[1])+(right-curr)24 if curr < len(walls) and walls[curr] == x_d[i][0]:25 curr += 126 l0 = max(x_d[i][0]-x_d[i][1], x_d[i-1][0]+1)27 while left0 < len(walls) and walls[left0] < l0:28 left0 += 129 l1 = max(min(x_d[i-1][0]+x_d[i-1][1], x_d[i][0]-1)+1,30 max(x_d[i][0]-x_d[i][1], x_d[i-1][0]+1))31 while left1 < len(walls) and walls[left1] < l1:32 left1 += 133 new_dp[0] = max(dp[0]+(curr-left0), dp[1]+(curr-left1))34 dp, new_dp = new_dp, dp35 return max(dp[0], dp[1])36