- 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
- 58 lines of C++ from the credited upstream file partition-array-to-minimize-xor.cpp.
- The implementation visibly relies on sequence storage, cached states.
- 8 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 {6public:7 int minXor(vector<int>& nums, int k) {8 static const int INF = numeric_limits<int>::max();9 10 vector<int> prefix(size(nums) + 1);11 for (int i = 0; i < size(nums); ++i) {12 prefix[i + 1] = prefix[i] ^ nums[i];13 }14 vector<int> dp(prefix);15 dp[0] = INF;16 for (int l = 2; l <= k; ++l){17 for (int i = size(nums); i >= l - 1; --i) {18 int mn = INF;19 for (int j = l - 1; j < i; ++j) {20 const auto& v = prefix[i] ^ prefix[j];21 const auto& mx = dp[j] > v ? dp[j] : v;22 if (mx < mn) {23 mn = mx;24 }25 }26 dp[i] = mn;27 }28 }29 return dp[size(nums)];30 }31};32 33343536class Solution2 {37public:38 int minXor(vector<int>& nums, int k) {39 static const int INF = numeric_limits<int>::max();40 41 vector<int> prefix(size(nums) + 1);42 for (int i = 0; i < size(nums); ++i) {43 prefix[i + 1] = prefix[i] ^ nums[i];44 }45 vector<int> dp(size(nums) + 1, INF);46 dp[0] = 0;47 for (int l = 1; l <= k; ++l){48 for (int i = size(nums); i >= l - 1; --i) {49 dp[i] = INF;50 for (int j = l - 1; j < i; ++j) {51 dp[i] = min(dp[i], max(dp[j], prefix[i] ^ prefix[j]));52 }53 }54 }55 return dp[size(nums)];56 }57};58