- Decide the key that represents the information needed later.
- Update its count or stored state while scanning the input.
- Use constant-time expected lookups to detect matches or assemble the result.
Code notes
- 39 lines of Java from the credited upstream file 3003.java.
- The implementation visibly relies on hash lookup, ordered lookup.
- 1 loop block detected.
Complexity
Expected hash operations are constant time, but the surrounding scan and the number of stored keys determine total work and memory.
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 maxPartitionsAfterOperations(String s, int k) {3 Map<Long, Integer> mem = new HashMap<>();4 return maxPartitionsAfterOperations(s, 0, true, 0, k, mem) + 1;5 }6 7 8 9 10 private int maxPartitionsAfterOperations(final String s, int i, boolean canChange, int mask,11 int k, Map<Long, Integer> mem) {12 if (i == s.length())13 return 0;14 15 Long key = (long) i << 27 | (canChange ? 1 : 0) << 26 | mask;16 if (mem.containsKey(key))17 return mem.get(key);18 19 20 int res = getRes(s, i, canChange, mask, 1 << (s.charAt(i) - 'a'), k, mem);21 22 23 if (canChange)24 for (int j = 0; j < 26; ++j)25 res = Math.max(res, getRes(s, i, false, mask, 1 << j, k, mem));26 27 mem.put(key, res);28 return res;29 }30 31 private int getRes(final String s, int i, boolean nextCanChange, int mask, int newBit, int k,32 Map<Long, Integer> mem) {33 final int newMask = mask | newBit;34 if (Integer.bitCount(newMask) > k) 35 return 1 + maxPartitionsAfterOperations(s, i + 1, nextCanChange, newBit, k, mem);36 return maxPartitionsAfterOperations(s, i + 1, nextCanChange, newMask, k, mem);37 }38}39