Maximum Number of Operations With the Same Score II - Problem

Given an array of integers called nums, you can perform any of the following operations while nums contains at least 2 elements:

  • Choose the first two elements of nums and delete them.
  • Choose the last two elements of nums and delete them.
  • Choose the first and the last elements of nums and 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.

Input & Output

Example 1 — Basic Case
$ Input: nums = [3,2,1,4,5]
Output: 2
💡 Note: First operation: remove first and last (3+5=8), array becomes [2,1,4]. Second operation: remove first and last (2+4=6≠8), or first two (2+1=3≠8), or last two (1+4=5≠8). Actually, we can remove 2+4=6 if we started with a different first operation. Let's try: remove first two (3+2=5), then remove first two again (1+4=5). Total: 2 operations with score 5.
Example 2 — Simple Case
$ Input: nums = [3,2,3]
Output: 1
💡 Note: We can remove first and last (3+3=6), leaving [2]. Only 1 operation possible since we need at least 2 elements.
Example 3 — No Valid Operations
$ Input: nums = [1,5]
Output: 1
💡 Note: Only one operation possible: remove first and last (1+5=6). Since there are no more elements, we get 1 operation total.

Constraints

  • 2 ≤ nums.length ≤ 2000
  • 1 ≤ nums[i] ≤ 1000

Visualization

Tap to expand
Max Operations with Same Score II INPUT Array nums: 3 i=0 2 i=1 1 i=2 4 i=3 5 i=4 3 Operations: 1. First two: 3+2 = 5 2. Last two: 4+5 = 9 3. First+Last: 3+5 = 8 Try each score as target using memoization ALGORITHM STEPS 1 Calculate 3 Scores First 2, Last 2, First+Last 2 DP with Memoization dp(left, right, target) 3 Try Each Operation If sum matches target 4 Return Max Count Among all 3 targets Target Score = 8 Op1: [3,2,1,4,5] --> 3+5=8 (OK) remove both Op2: [2,1,4] --> 2+1=3, 1+4=5, 2+4=6 --> No match! Stop Result: 1 operation FINAL RESULT Testing All Target Scores: Target = 5 (3+2) Op1: 3+2=5, Op2: 1+4=5 2 Target = 9 (4+5) Op1: 4+5=9, then stuck 1 Target = 8 (3+5) Op1: 3+5=8, then stuck 1 OUTPUT 2 Maximum operations with same score (5) Key Insight: Use memoization with dp(left, right) to avoid recalculating subproblems. Only 3 possible target scores exist (from initial operations). For each target, recursively try all 3 operations and take the maximum. Time: O(n^2) for each target. Return max across all targets. TutorialsPoint - Maximum Number of Operations With the Same Score II | Optimal Solution (DP + Memoization)
Asked in
Google 15 Meta 12 Amazon 8
23.5K Views
Medium Frequency
~25 min Avg. Time
847 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen