Untitled

mail@pastecode.io avatar
unknown
plain_text
18 days ago
1.7 kB
5
Indexable
Never
class Solution {
public:
    int N;
    vector<vector<int>> memo; // Adding memoization
    int helper(int start, int end, vector<int>& nums, int fixed) {
        if (end <= start) return 0;
        if (memo[start][end] != -1) return memo[start][end]; // Use memoized value if available
        
        int a = 0, b = 0, c = 0;
        if (start + 1 < N && nums[start] + nums[start + 1] == fixed) {
            a = 1 + helper(start + 2, end, nums, fixed); // Each valid operation counts as 1
        }
        if (end - 1 >= 0 && nums[end] + nums[end - 1] == fixed) {
            b = 1 + helper(start, end - 2, nums, fixed);
        }
        if (nums[start] + nums[end] == fixed) {
            c = 1 + helper(start + 1, end - 1, nums, fixed);
        }
        memo[start][end] = max(a, max(b, c)); // Memoize the result
        return memo[start][end];
    }
    int maxOperations(vector<int>& nums) {
        N = nums.size();
        memo.assign(N, vector<int>(N, -1)); // Initialize memoization array

        if (N < 2) return 0;
        
        int maxOps = 0;
        // Instead of trying every possible fixed value, we focus on a single series of operations per call
        maxOps = max(maxOps, helper(0, N - 1, nums, nums[0] + nums[1]));
        memo.assign(N, vector<int>(N, -1)); // Initialize memoization array
        maxOps = max(maxOps, helper(0, N - 1, nums, nums[N - 1] + nums[N - 2]));
        memo.assign(N, vector<int>(N, -1)); // Initialize memoization array
        maxOps = max(maxOps, helper(0, N - 1, nums, nums[0] + nums[N - 1]));
        
        return maxOps; // No need to divide by 2 since we count operations directly
    }
};
Leave a Comment