- 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
- 32 lines of Java from the credited upstream file 3040.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 maxOperations(int[] nums) {3 final int n = nums.length;4 Map<String, Integer> mem = new HashMap<>();5 return Math.max(Math.max(maxOperations(nums, 0, n - 1, nums[0] + nums[1], mem),6 maxOperations(nums, 0, n - 1, nums[n - 1] + nums[n - 2], mem)),7 maxOperations(nums, 0, n - 1, nums[0] + nums[n - 1], mem));8 }9 10 11 12 private int maxOperations(int[] nums, int i, int j, int score, Map<String, Integer> mem) {13 if (i >= j)14 return 0;15 final String key = hash(i, j, score);16 if (mem.containsKey(key))17 return mem.get(key);18 final int deleteFirstTwo =19 nums[i] + nums[i + 1] == score ? 1 + maxOperations(nums, i + 2, j, score, mem) : 0;20 final int deleteLastTwo =21 nums[j] + nums[j - 1] == score ? 1 + maxOperations(nums, i, j - 2, score, mem) : 0;22 final int deleteFirstAndLast =23 nums[i] + nums[j] == score ? 1 + maxOperations(nums, i + 1, j - 1, score, mem) : 0;24 mem.put(key, Math.max(Math.max(deleteFirstTwo, deleteLastTwo), deleteFirstAndLast));25 return mem.get(key);26 }27 28 private String hash(int i, int j, int score) {29 return i + "," + j + "," + score;30 }31}32