- 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
- 40 lines of C++ from the credited upstream file 3117.cpp.
- The implementation visibly relies on sequence storage, hash 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:3 int minimumValueSum(vector<int>& nums, vector<int>& andValues) {4 vector<vector<unordered_map<int, int>>> mem(5 nums.size(), vector<unordered_map<int, int>>(andValues.size()));6 const int ans = minimumValueSum(nums, andValues, 0, 0, kFullMask, mem);7 return ans == kInf ? -1 : ans;8 }9 10 private:11 static constexpr int kInf = 1'000'000'000;12 static constexpr int kFullMask = (1 << 17) - 1;13 14 15 16 int minimumValueSum(const vector<int>& nums, const vector<int>& andValues,17 int i, int j, int mask,18 vector<vector<unordered_map<int, int>>>& mem) {19 if (i == nums.size() && j == andValues.size())20 return 0;21 if (i == nums.size() || j == andValues.size())22 return kInf;23 if (const auto it = mem[i][j].find(mask); it != mem[i][j].cend())24 return it->second;25 mask &= nums[i];26 if (mask < andValues[j])27 return mem[i][j][mask] = kInf;28 if (mask == andValues[j])29 30 31 return mem[i][j][mask] =32 min(minimumValueSum(nums, andValues, i + 1, j, mask, mem),33 nums[i] + minimumValueSum(nums, andValues, i + 1, j + 1,34 kFullMask, mem));35 36 return mem[i][j][mask] =37 minimumValueSum(nums, andValues, i + 1, j, mask, mem);38 };39};40