- 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
- 49 lines of Java from the credited upstream file 3333.java.
- The implementation visibly relies on sequence storage, cached states.
- 3 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 possibleStringCount(String word, int k) {3 List<Integer> groups = getConsecutiveLetters(word);4 final int totalCombinations =5 (int) groups.stream().mapToLong(Integer::longValue).reduce(1L, (a, b) -> a * b % MOD);6 if (k <= groups.size())7 return totalCombinations;8 9 10 11 int[] dp = new int[k];12 dp[0] = 1; 13 14 for (int i = 0; i < groups.size(); ++i) {15 int[] newDp = new int[k];16 int windowSum = 0;17 int group = groups.get(i);18 for (int j = i; j < k; ++j) {19 newDp[j] = (newDp[j] + windowSum) % MOD;20 windowSum = (windowSum + dp[j]) % MOD;21 if (j >= group)22 windowSum = (windowSum - dp[j - group] + MOD) % MOD;23 }24 dp = newDp;25 }26 27 final int invalidCombinations = Arrays.stream(dp).reduce(0, (a, b) -> (a + b) % MOD);28 return (totalCombinations - invalidCombinations + MOD) % MOD;29 }30 31 private static final int MOD = 1_000_000_007;32 33 34 35 private List<Integer> getConsecutiveLetters(final String word) {36 List<Integer> groups = new ArrayList<>();37 int group = 1;38 for (int i = 1; i < word.length(); ++i)39 if (word.charAt(i) == word.charAt(i - 1)) {40 ++group;41 } else {42 groups.add(group);43 group = 1;44 }45 groups.add(group);46 return groups;47 }48}49