- 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
- 68 lines of Python from the credited upstream file 1659.py.
- The implementation visibly relies on hash lookup, 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 getMaxGridHappiness(3 self,4 m: int,5 n: int,6 introvertsCount: int,7 extrovertsCount: int,8 ) -> int:9 def getPlacementCost(10 i: int,11 j: int,12 inMask: int,13 exMask: int,14 diff: int,15 ) -> int:16 """Calculates the cost based on left and up neighbors.17 18 The `diff` parameter represents the happiness change due to the current19 placed person in (i, j). We add `diff` each time we encounter a neighbor20 (left or up) who is already placed.21 22 1. If the neighbor is an introvert, we subtract 30 from cost.23 2. If the neighbor is an extrovert, we add 20 to from cost.24 """25 cost = 026 if i > 0:27 if (1 << (n - 1)) & inMask:28 cost += diff - 3029 if (1 << (n - 1)) & exMask:30 cost += diff + 2031 if j > 0:32 if 1 & inMask:33 cost += diff - 3034 if 1 & exMask:35 cost += diff + 2036 return cost37 38 @functools.lru_cache(None)39 def dp(40 pos: int, inMask: int, exMask: int, inCount: int, exCount: int41 ) -> int:42 43 44 45 46 47 i, j = divmod(pos, n)48 if i == m:49 return 050 51 shiftedInMask = (inMask << 1) & ((1 << n) - 1)52 shiftedExMask = (exMask << 1) & ((1 << n) - 1)53 54 skip = dp(pos + 1, shiftedInMask, shiftedExMask, inCount, exCount)55 placeIntrovert = (56 120 + getPlacementCost(i, j, inMask, exMask, -30) +57 dp(pos + 1, shiftedInMask + 1, shiftedExMask, inCount - 1, exCount)58 if inCount > 059 else -math.inf)60 placeExtrovert = (61 40 + getPlacementCost(i, j, inMask, exMask, 20) +62 dp(pos + 1, shiftedInMask, shiftedExMask + 1, inCount, exCount - 1)63 if exCount > 064 else -math.inf)65 return max(skip, placeIntrovert, placeExtrovert)66 67 return dp(0, 0, 0, introvertsCount, extrovertsCount)68