- 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
- 49 lines of Python from the credited upstream file maximum-consistent-columns-in-a-grid.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 4import bisect5 6 78class Solution(object):9 def maxConsistentColumns(self, grid, limit):10 lookup = [(1<<len(grid[0]))-1]*len(grid[0])11 for i in xrange(len(grid)):12 idxs = sorted(xrange(len(grid[0])), key=lambda j: grid[i][j])13 arr = [grid[i][j] for j in idxs]14 prefix = [0]*(len(grid[0])+1) 15 for j in xrange(len(grid[0])):16 prefix[j+1] = prefix[j]|(1<<idxs[j])17 for j in xrange(len(grid[0])):18 lookup[j] &= prefix[bisect.bisect_right(arr, grid[i][j]+limit)]^prefix[bisect.bisect_left(arr, grid[i][j]-limit)]19 dp = [1]*len(grid[0])20 for j in xrange(len(grid[0])):21 mx = 022 mask = lookup[j]&((1<<j)-1)23 while mask:24 k = (mask&-mask).bit_length()-125 mx = max(mx, dp[k])26 mask ^= (mask&-mask)27 dp[j] = mx+128 return max(dp)29 30 31323334class Solution2(object):35 def maxConsistentColumns(self, grid, limit):36 """37 :type grid: List[List[int]]38 :type limit: int39 :rtype: int40 """41 dp = [1]*len(grid[0])42 for i in xrange(len(grid[0])):43 for j in xrange(i):44 if dp[j]+1 <= dp[i]:45 continue46 if all(abs(row[i]-row[j]) <= limit for row in grid):47 dp[i] = dp[j]+148 return max(dp)49