Input: nums =[3,2,1,2,3,4]Output: 3Explanation: We perform the following operations:- Delete the first two elements,with score 3+2=5, nums =[1,2,3,4].- Delete the first and the last elements,with score 1+4=5, nums =[2,3].- Delete the first and the last elements,with score 2+3=5, nums =[].We are unable to perform any more operations as nums is empty.
Input: nums =[3,2,6,1,4]Output: 2Explanation: We perform the following operations:- Delete the first two elements,with score 3+2=5, nums =[6,1,4].- Delete the last two elements,with score 1+4=5, nums =[6].It can be proven that we can perform at most 2 operations.
At each step, you can remove the first two, last two, or first and last elements. The score for each operation must be the same. Try all possible first moves, then recursively check if you can continue with the same score. Use memoization to avoid recomputation.
For all possible ways to remove two elements at the start, end, or both, compute the score and recursively try to maximize the number of operations with that score.
Use memoization to cache results for (left, right, score).
For each possible initial operation, recursively try all valid next operations with the same score.
from functools import cache
classSolution:
defmaxOperations(self, nums: list[int]) -> int:
n = len(nums)
@cachedefdfs(l: int, r: int, score: int) -> int:
if r - l +1<2:
return0 res =0if l +1<= r and nums[l] + nums[l+1] == score:
res = max(res, 1+ dfs(l+2, r, score))
if r -1>= l and nums[r] + nums[r-1] == score:
res = max(res, 1+ dfs(l, r-2, score))
if l < r and nums[l] + nums[r] == score:
res = max(res, 1+ dfs(l+1, r-1, score))
return res
ans =0if n <2:
return0 ans = max(ans, 1+ dfs(2, n-1, nums[0] + nums[1]))
ans = max(ans, 1+ dfs(0, n-3, nums[-1] + nums[-2]))
ans = max(ans, 1+ dfs(1, n-2, nums[0] + nums[-1]))
return ans
1
// Omitted for brevity, similar logic as C++ using recursion and memoization.
1
// Omitted for brevity, similar logic as C++ using recursion and memoization.