- 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
- 31 lines of Java from the credited upstream file 3276.java.
- The implementation visibly relies on sequence storage, hash lookup, ordered lookup.
- 3 loop blocks 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 maxScore(List<List<Integer>> grid) {3 Map<Integer, Set<Integer>> numToIndices = new HashMap<>();4 for (int index = 0; index < grid.size(); ++index)5 for (final int num : grid.get(index)) {6 numToIndices.putIfAbsent(num, new HashSet<>());7 numToIndices.get(num).add(index);8 }9 int[][] mem = new int[numToIndices.size()][1 << grid.size()];10 return maxScore(new ArrayList<>(numToIndices.entrySet()), 0, 0, mem);11 }12 13 14 15 private int maxScore(List<Map.Entry<Integer, Set<Integer>>> numToIndices, int i, int mask,16 int[][] mem) {17 if (i == numToIndices.size())18 return 0;19 if (mem[i][mask] != 0)20 return mem[i][mask];21 22 int res = maxScore(numToIndices, i + 1, mask, mem);23 for (int index : numToIndices.get(i).getValue())24 if ((mask >> index & 1) == 0)25 26 res = Math.max(res, numToIndices.get(i).getKey() +27 maxScore(numToIndices, i + 1, mask | (1 << index), mem));28 return mem[i][mask] = res;29 }30}31