- 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
- 42 lines of Java from the credited upstream file 3117.java.
- The implementation visibly relies on sequence storage, hash lookup, ordered lookup.
- No explicit 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 minimumValueSum(int[] nums, int[] andValues) {3 Map<Integer, Integer>[][] mem = new Map[nums.length][andValues.length];4 Arrays.stream(mem).forEach(A -> Arrays.setAll(A, j -> new HashMap<>()));5 final int ans = minimumValueSum(nums, andValues, 0, 0, FULL_MASK, mem);6 return ans == INF ? -1 : ans;7 }8 9 private static final int INF = 1_000_000_000;10 private static final int FULL_MASK = (1 << 17) - 1;11 12 13 14 private int minimumValueSum(int[] nums, int[] andValues, int i, int j, int mask,15 Map<Integer, Integer>[][] mem) {16 if (i == nums.length && j == andValues.length)17 return 0;18 if (i == nums.length || j == andValues.length)19 return INF;20 if (mem[i][j].containsKey(mask))21 return mem[i][j].get(mask);22 mask &= nums[i];23 if (mask < andValues[j]) {24 mem[i][j].put(mask, INF);25 return INF;26 }27 if (mask == andValues[j]) {28 29 30 final int res =31 Math.min(minimumValueSum(nums, andValues, i + 1, j, mask, mem),32 nums[i] + minimumValueSum(nums, andValues, i + 1, j + 1, FULL_MASK, mem));33 mem[i][j].put(mask, res);34 return res;35 }36 37 final int res = minimumValueSum(nums, andValues, i + 1, j, mask, mem);38 mem[i][j].put(mask, res);39 return res;40 }41}42