Top Down DP
Top down
# Top down

```javascript []
const maxOperations = (nums) => {
  const memo = Array.from({ length: nums.length }, () => Array(nums.length).fill(0));

  function dp(left, right, prevSum) {
    if (left >= right) return 0;

    if (memo[left][right]) return memo[left][right];

    let maxOps = 0; //Track the maximum operations 

    // Check if the pair at (left, left + 1) forms a valid operation
    if (nums[left] + nums[left + 1] === prevSum) {
      maxOps = Math.max(maxOps, dp(left + 2, right, prevSum) + 1);
    }

    // Check if the pair at (left, right) forms a valid operation
    if (nums[left] + nums[right] === prevSum) {
      maxOps = Math.max(maxOps, dp(left + 1, right - 1, prevSum) + 1);
    }

    // Check if the pair at (right - 1, right) forms a valid operation
    if (nums[right] + nums[right - 1] === prevSum) {
      maxOps = Math.max(maxOps, dp(left, right - 2, prevSum) + 1);
    }

    return (memo[left][right] = maxOps);
  }

  // Calculate the maximum operations
  const end = nums.length - 1;
  return Math.max(
    dp(2, end, nums[0] + nums[1]) + 1, // First two elements as the target sum
    dp(1, end - 1, nums[0] + nums[end]) + 1, // First and last elements as the target sum
    dp(0, end - 2, nums[end] + nums[end - 1]) + 1 // Last two elements as the target sum
  );
};
```
['Array', 'Dynamic Programming', 'Memoization', 'JavaScript']