- 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
- 59 lines of Python from the credited upstream file maximum-score-using-exactly-k-pairs.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 maxScore(self, nums1, nums2, k):7 """8 :type nums1: List[int]9 :type nums2: List[int]10 :type k: int11 :rtype: int12 """13 NEG_INF = float("-inf")14 if len(nums1) < len(nums2):15 nums1, nums2 = nums2, nums116 dp = [[NEG_INF]*(k+1) for _ in xrange(len(nums2)+1)]17 for j in xrange(len(nums2)+1):18 dp[j][0] = 019 new_dp = [[NEG_INF]*(k+1) for _ in xrange(len(nums2)+1)]20 for i in xrange(len(nums1)):21 for j in xrange(len(nums2)+1):22 new_dp[j][0] = 023 for j in xrange(len(nums2)):24 score = nums1[i]*nums2[j]25 for c in xrange(min(i+1, j+1, k)):26 new_dp[j+1][c+1] = max(27 new_dp[j][c+1],28 dp[j+1][c+1],29 dp[j][c]+score30 )31 dp, new_dp = new_dp, dp32 return dp[-1][-1]33 34 35363738class Solution(object):39 def maxScore(self, nums1, nums2, k):40 """41 :type nums1: List[int]42 :type nums2: List[int]43 :type k: int44 :rtype: int45 """46 NEG_INF = float("-inf") 47 dp = [[NEG_INF]*len(nums2) for _ in xrange(len(nums1))]48 new_dp = [[NEG_INF]*len(nums2) for _ in xrange(len(nums1))]49 for c in xrange(k):50 for i in xrange(c, len(nums1)):51 for j in xrange(c, len(nums2)):52 new_dp[i][j] = max(53 new_dp[i][j-1] if j-1 >= c else NEG_INF,54 new_dp[i-1][j] if i-1 >= c else NEG_INF,55 (dp[i-1][j-1] if c else 0) + nums1[i]*nums2[j]56 )57 dp, new_dp = new_dp, dp58 return dp[-1][-1]59