#3038

Maximum Number of Operations With the Same Score I

Easy
ArraySimulationHash MapArray
LeetCode ↗

Approaches

Brute ForceOptimal
Complexity Comparison
Brute ForceOptimal Solution
Time
O(n²)
O(n²)
Space
O(1)
O(n)
💡

Intuition

Time O(n²)Space O(n)

The optimal approach involves using a frequency map to count occurrences of each possible score. This allows us to determine how many pairs can produce the same score efficiently without simulating each operation.

⚙️

Algorithm

3 steps
  1. 1Step 1: Create a frequency map to count how many times each possible score can be formed by summing pairs of elements.
  2. 2Step 2: For each unique score in the frequency map, calculate how many pairs can be formed and keep track of the maximum number of operations.
  3. 3Step 3: Return the maximum count of operations found.
solution.py10 lines
1from collections import defaultdict
2
3def maxOperations(nums):
4    score_count = defaultdict(int)
5    n = len(nums)
6    for i in range(n):
7        for j in range(i + 1, n):
8            score = nums[i] + nums[j]
9            score_count[score] += 1
10    return max(score_count.values(), default=0)

Complexity note: While the time complexity remains O(n²) due to the nested loops, the space complexity improves to O(n) because we store the scores in a frequency map instead of modifying the original array.

  • 1The score of each operation must match the previous score for it to count.
  • 2Using a frequency map allows us to efficiently track possible scores.

Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.