- 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 Java from the credited upstream file 1787.java.
- The implementation visibly relies on sequence storage, hash lookup, ordered lookup, cached states.
- 6 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.
1class Solution {2 public int minChanges(int[] nums, int k) {3 final int MAX = 1024;4 final int n = nums.length;5 6 Map<Integer, Integer>[] counts = new Map[k];7 8 int[][] dp = new int[k][MAX];9 10 for (int i = 0; i < k; ++i)11 counts[i] = new HashMap<>();12 13 for (int i = 0; i < n; ++i)14 counts[i % k].merge(nums[i], 1, Integer::sum);15 16 Arrays.stream(dp).forEach(A -> Arrays.fill(A, n));17 18 19 for (int j = 0; j < MAX; ++j)20 dp[k - 1][j] = countAt(n, k, k - 1) - counts[k - 1].getOrDefault(j, 0);21 22 for (int i = k - 2; i >= 0; --i) {23 24 25 final int changeAll = countAt(n, k, i) + Arrays.stream(dp[i + 1]).min().getAsInt();26 for (int j = 0; j < MAX; ++j) {27 dp[i][j] = changeAll;28 for (Map.Entry<Integer, Integer> entry : counts[i].entrySet()) {29 final int num = entry.getKey();30 final int freq = entry.getValue();31 32 final int cost = countAt(n, k, i) - freq;33 dp[i][j] = Math.min(dp[i][j], dp[i + 1][j ^ num] + cost);34 }35 }36 }37 38 return dp[0][0];39 }40 41 private int countAt(int n, int k, int i) {42 return n / k + (n % k > i ? 1 : 0);43 }44}45