C++ Top Down Recursive DP
Code\nC++\nclass Solution {\npublic:\n    int n;\n    int sum;\n    int mem[2001][2001];\n    int rec(int i, int j, vector<int> &nums) {\n        if(i >= j) ret
# Code\n```C++\nclass Solution {\npublic:\n    int n;\n    int sum;\n    int mem[2001][2001];\n    int rec(int i, int j, vector<int> &nums) {\n        if(i >= j) return 0;\n        if(mem[i][j] != -1) return  mem[i][j];\n        int tmp = 0;\n        if(nums[i]+nums[i+1] == sum) tmp = 1+rec(i+2, j, nums);\n        if(nums[j-1]+nums[j] == sum) tmp = max(tmp, 1+rec(i, j-2, nums));\n        if(nums[i]+nums[j] == sum) tmp = max(tmp, 1+rec(i+1, j-1, nums));\n        return mem[i][j] = tmp;\n    }\n    int maxOperations(vector<int>& nums) {\n        n = nums.size();\n        int sums[3];\n        sums[0] = nums[0]+nums[1];\n        sums[1] = nums[n-2]+nums[n-1];\n        sums[2] = nums[0]+nums[n-1];\n        int ans = 0;\n        for(int i = 0; i<3; i++) {\n            sum = sums[i];\n            memset(mem, -1, sizeof(mem));\n            ans = max(ans, rec(0, n-1, nums));\n        }\n        return ans;\n    }\n};\n```\n\n```C++\n// takes more time and memory\nclass Solution {\npublic:\n    static const int lim = 2*1e3+1;\n    int n;\n    int mem[lim][lim][3];\n    int sums[3];\n    int rec(int i, int j, int prev, vector<int> &nums) {\n        if(i >= j) return 0;\n        if(mem[i][j][prev] != -1) return  mem[i][j][prev];\n        int tmp = 0;\n        if(nums[i]+nums[i+1] == sums[prev]) tmp = 1+rec(i+2, j, prev, nums);\n        if(nums[j-1]+nums[j] == sums[prev]) tmp = max(tmp, 1+rec(i, j-2, prev, nums));\n        if(nums[i]+nums[j] == sums[prev]) tmp = max(tmp, 1+rec(i+1, j-1, prev, nums));\n        return mem[i][j][prev] = tmp;\n    }\n    int maxOperations(vector<int>& nums) {\n        n = nums.size();\n        sums[0] = nums[0]+nums[1];\n        sums[1] = nums[n-2]+nums[n-1];\n        sums[2] = nums[0]+nums[n-1];\n        memset(mem, -1, sizeof(mem));\n        int ans = 0;\n        for(int i = 0; i<3; i++) {\n            ans = max(ans, rec(0, n-1, i, nums));\n        }\n        return ans;\n    }\n};\n```
['Recursion', 'Memoization', 'C++']