- 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 maximize-palindrome-length-from-subsequences.py.
- The implementation visibly relies on 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 4class Solution(object):5 def longestPalindrome(self, word1, word2):6 """7 :type word1: str8 :type word2: str9 :rtype: int10 """11 s = word1+word212 dp = [[0]*len(s) for _ in xrange(len(s))]13 result = 014 for j in xrange(len(s)):15 dp[j][j] = 116 for i in reversed(xrange(j)):17 if s[i] == s[j]:18 dp[i][j] = 2 if i+1 == j else dp[i+1][j-1] + 219 if i < len(word1) <= j:20 result = max(result, dp[i][j])21 else:22 dp[i][j] = max(dp[i+1][j], dp[i][j-1])23 return result24 25 262728class Solution2(object):29 def longestPalindrome(self, word1, word2):30 """31 :type word1: str32 :type word2: str33 :rtype: int34 """35 s = word1+word236 dp = [[0]*len(s) for _ in xrange(len(s))]37 for j in xrange(len(s)):38 dp[j][j] = 139 for i in reversed(xrange(j)):40 if s[i] == s[j]:41 dp[i][j] = 2 if i+1 == j else dp[i+1][j-1] + 242 else:43 dp[i][j] = max(dp[i+1][j], dp[i][j-1])44 return max([dp[i][j] for i in xrange(len(word1)) for j in xrange(len(word1), len(s)) if s[i] == s[j]] or [0])45