- 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
- 52 lines of Python from the credited upstream file partition-array-to-minimize-xor.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 minXor(self, nums, k):7 """8 :type nums: List[int]9 :type k: int10 :rtype: int11 """12 INF = float("inf")13 prefix = [0]*(len(nums)+1)14 for i in xrange(len(nums)):15 prefix[i+1] = prefix[i]^nums[i]16 dp = prefix[:]17 dp[0] = INF18 for l in xrange(2, k+1):19 for i in reversed(xrange(l-1, len(dp))):20 mn = INF21 for j in xrange(l-1, i):22 v = prefix[i]^prefix[j]23 mx = dp[j] if dp[j] > v else v24 if mx < mn:25 mn = mx26 dp[i] = mn27 return dp[-1]28 29 30313233class Solution2(object):34 def minXor(self, nums, k):35 """36 :type nums: List[int]37 :type k: int38 :rtype: int39 """40 INF = float("inf")41 prefix = [0]*(len(nums)+1)42 for i in xrange(len(nums)):43 prefix[i+1] = prefix[i]^nums[i]44 dp = [INF]*(len(nums)+1)45 dp[0] = 046 for l in xrange(1, k+1):47 for i in reversed(xrange(l-1, len(dp))):48 dp[i] = INF49 for j in xrange(l-1, i):50 dp[i] = min(dp[i], max(dp[j], prefix[i]^prefix[j]))51 return dp[-1]52