Maximum Number of Operations With the Same Score II Problem
Description
LeetCode Problem 3040.
Given an array of integers called nums, you can perform any of the following operation while nums contains at least 2 elements:
- Choose the first two elements of
numsand delete them. - Choose the last two elements of
numsand delete them. - Choose the first and the last elements of
numsand delete them.
The score of the operation is the sum of the deleted elements.
Your task is to find the maximum number of operations that can be performed, such that all operations have the same score.
Return the maximum number of operations possible that satisfy the condition mentioned above.
Example 1:
Input: nums = [3,2,1,2,3,4]
Output: 3
Explanation: 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.
Example 2:
Input: nums = [3,2,6,1,4]
Output: 2
Explanation: 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.
Constraints:
2 <= nums.length <= 20001 <= nums[i] <= 1000
Solution
Approach: Memoized Search
The first operation fixes the score, and it can only be one of three sums: nums[0] + nums[1], nums[0] + nums[n-1] or nums[n-2] + nums[n-1]. For each candidate score s, apply that first operation and solve what remains with memoization.
dfs(i, j) is the most operations possible on the subarray nums[i..j] when every score must equal s:
- If
j - i < 1, fewer than two elements remain, so return0. - If
nums[i] + nums[i+1] == s, deleting the first two gives1 + dfs(i+2, j). - If
nums[i] + nums[j] == s, deleting both ends gives1 + dfs(i+1, j-1). - If
nums[j-1] + nums[j] == s, deleting the last two gives1 + dfs(i, j-2). - Return the largest option (or
0).
The answer is 1 plus the best result over the three starting choices.
Complexity: time O(n^2), space O(n^2).
from functools import lru_cache
class Solution:
def maxOperations(self, nums: List[int]) -> int:
@lru_cache(None)
def dfs(i: int, j: int, s: int) -> int:
if j - i < 1:
return 0
ans = 0
if nums[i] + nums[i + 1] == s:
ans = max(ans, 1 + dfs(i + 2, j, s))
if nums[i] + nums[j] == s:
ans = max(ans, 1 + dfs(i + 1, j - 1, s))
if nums[j - 1] + nums[j] == s:
ans = max(ans, 1 + dfs(i, j - 2, s))
return ans
n = len(nums)
a = dfs(2, n - 1, nums[0] + nums[1])
b = dfs(0, n - 3, nums[-1] + nums[-2])
c = dfs(1, n - 2, nums[0] + nums[-1])
return 1 + max(a, b, c)