Maximum Number of Operations With the Same Score I - Problem

You are given an array of integers nums. Consider the following operation:

Delete the first two elements nums[0] and nums[1] and define the score of the operation as the sum of these two elements.

You can perform this operation until nums contains fewer than two elements. Additionally, the same score must be achieved in all operations.

Return the maximum number of operations you can perform.

Input & Output

Example 1 — Basic Case
$ Input: nums = [3,2,1,4,5,2]
Output: 2
💡 Note: First pair: 3+2=5, second pair: 1+4=5, third pair: 5+2=7≠5, so we stop. Total operations: 2.
Example 2 — Single Operation
$ Input: nums = [3,2,6,1]
Output: 1
💡 Note: First pair: 3+2=5, second pair: 6+1=7≠5, so we stop after 1 operation.
Example 3 — All Same Score
$ Input: nums = [1,4,2,3]
Output: 2
💡 Note: First pair: 1+4=5, second pair: 2+3=5. Both pairs have same score, so 2 operations total.

Constraints

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

Visualization

Tap to expand
Maximum Operations With Same Score INPUT Array: nums 3 [0] 2 [1] 1 [2] 4 [3] 5 [4] 2 [5] Length = 6 elements Max possible ops = 3 Operation Rule: Delete nums[0] + nums[1] Score = sum of deleted All scores must match! ALGORITHM STEPS 1 Get Target Score target = nums[0]+nums[1] target = 3 + 2 = 5 2 Op 1: Delete [3,2] 3+2=5 matches target count = 1, OK 3 Op 2: Delete [1,4] 1+4=5 matches target count = 2, OK 4 Op 3: Check [5,2] 5+2=7 != 5 (target) STOP! Score mismatch Array State Changes: Start: [3,2,1,4,5,2] After Op1: [1,4,5,2] After Op2: [5,2] Op3 fails: 5+2=7 FINAL RESULT Operations Completed: Op 1: [3,2] --> Score: 5 OK - matches target Op 2: [1,4] --> Score: 5 OK - matches target Op 3: [5,2] --> Score: 7 FAIL - different score OUTPUT 2 Maximum operations with same score (5) = 2 Key Insight: Early Termination Optimization The first operation sets the target score. All subsequent operations must match this exact score. We can terminate early as soon as we find a pair that doesn't match the target score. Time complexity: O(n) in worst case, but often terminates earlier. Space complexity: O(1). TutorialsPoint - Maximum Number of Operations With the Same Score I | Early Termination Optimization
Asked in
Microsoft 25 Amazon 20 Google 15
30.3K Views
Medium Frequency
~15 min Avg. Time
890 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