- 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 3040.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 maxOperations(vector<int>& nums) {4 const int n = nums.size();5 unordered_map<string, int> mem;6 return max({maxOperations(nums, 0, n - 1, nums[0] + nums[1], mem),7 maxOperations(nums, 0, n - 1, nums[n - 1] + nums[n - 2], mem),8 maxOperations(nums, 0, n - 1, nums[0] + nums[n - 1], mem)});9 }10 11 private:12 13 14 int maxOperations(const vector<int>& nums, int i, int j, int score,15 unordered_map<string, int>& mem) {16 if (i >= j)17 return 0;18 const string key = hash(i, j, score);19 if (const auto it = mem.find(key); it != mem.end())20 return it->second;21 const int deleteFirstTwo =22 nums[i] + nums[i + 1] == score23 ? 1 + maxOperations(nums, i + 2, j, score, mem)24 : 0;25 const int deleteLastTwo =26 nums[j] + nums[j - 1] == score27 ? 1 + maxOperations(nums, i, j - 2, score, mem)28 : 0;29 const int deleteFirstAndLast =30 nums[i] + nums[j] == score31 ? 1 + maxOperations(nums, i + 1, j - 1, score, mem)32 : 0;33 return mem[key] = max({deleteFirstTwo, deleteLastTwo, deleteFirstAndLast});34 }35 36 string hash(int i, int j, int score) {37 return to_string(i) + "," + to_string(j) + "," + to_string(score);38 }39};40