Problem Description
Given an integer array nums, you are allowed to repeatedly perform an operation while nums has at least 2 elements. In each operation you may choose one of the following choices to remove two numbers from the current (contiguous) array: • Remove the first two elements. • Remove the last two elements. • Remove the first and the last elements. The score of an operation is defined as the sum of the two deleted elements. Your task is to obtain the maximum number of operations you can perform so that all operations have the same score.
Key Insights
- Because removals always occur at the ends, after each operation the remaining array is contiguous.
- Any valid sequence of removals induces a partition of the array into pairs, where each pair is either a “left‐pair” (first two elements), a “right‐pair” (last two elements), or an “outer pair” (first and last element).
- All pairs must have the same sum S. Thus, it makes sense to “fix” a candidate target S and then check the maximum number of valid operations possible.
- For each fixed S candidate (which comes from sums of array elements), one can use a dynamic programming approach over subarrays (tracked by indices l and r) which represents the maximum operations possible from that subarray under the constraint that every chosen pair has sum S.
Space and Time Complexity
Time Complexity: O(U * n²), where n is the length of nums and U is the number of candidate sums (typically derived from pairs in the array).
Space Complexity: O(n²) for the DP table (per candidate S).
Solution
We solve the problem by “fixing” a target sum S and then using DP over intervals. Define dp(l, r) as the maximum number of valid operations we can perform on the subarray nums[l…r] if we require every pair removal to have score S. The valid transitions are:
• If the first two elements sum to S (i.e. nums[l] + nums[l+1] == S), then one operation is performed and we continue with dp(l+2, r).
• If the outer two elements sum to S (nums[l] + nums[r] == S), then one operation is executed and we move to dp(l+1, r-1).
• If the last two elements sum to S (nums[r-1] + nums[r] == S), then one operation is done and we proceed with dp(l, r-2).
We compute dp(0, n-1) for every candidate S (only considering those values that actually appear as a pair sum in nums) and take the maximum result.
Key details include ensuring that the subarray has at least 2 elements before attempting an operation and handling the boundaries correctly. This DP naturally reflects the fact that the removal always happens at the ends of the current array, keeping it contiguous.