Untitled

mail@pastecode.io avatar
unknown
plain_text
a month ago
1.8 kB
4
Indexable
Never
class Solution {
public:
    int helper(vector<int>& nums, int left, int right, int sum, vector<vector<int>>& vec) {
        if(left >= right)
            return 0;
        if (vec[left][right] != -1) {
            return vec[left][right];
        }
        // Reduce overcounting

        int step_left = 0;
        if (left + 1 < nums.size()) {
            if (nums[left] + nums[left + 1] == sum) {
                step_left = 1 + helper(nums, left + 2, right, sum, vec);
            }
        }
        // right two
        int step_right = 0;
        if (right - 1 >= 0) {
            if (nums[right] + nums[right - 1] == sum) {
                step_right = 1 + helper(nums, left, right - 2, sum, vec);
            }
        }

        int step_left_right = 0;
        // most left and most right
        if (nums[left] + nums[right] == sum) {
            step_left_right = 1 + helper(nums, left + 1, right - 1, sum, vec);
        }

        int max_cur_step = max(step_left, max(step_right, step_left_right));
        vec[left][right] = max_cur_step;
        return vec[left][right];
    }

    int maxOperations(vector<int>& nums) {
        int size = nums.size();

        vector<vector<int>> vec(size, vector<int>(size, -1));
        int sum_of_left_two = nums[0] + nums[1];
        int sum_of_right_two = nums[nums.size() - 1] + nums[nums.size() - 2];
        int sum_of_l_and_r = nums[0] + nums[nums.size() - 1];
        int l = helper(nums, 0, size - 1, sum_of_left_two, vec);
        vec.assign(size, vector<int>(size, -1));
        int r = helper(nums, 0, size - 1, sum_of_right_two, vec);
        vec.assign(size, vector<int>(size, -1));
        int lr = helper(nums, 0, size - 1, sum_of_l_and_r, vec);
        return max(l, max(r, lr));
    }
};
Leave a Comment