#3040

Maximum Number of Operations With the Same Score II

Medium
ArrayDynamic ProgrammingMemoizationDynamic ProgrammingTwo Pointers
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 solution uses dynamic programming to track the maximum number of operations that can be performed for each possible score. This reduces redundant calculations and efficiently narrows down the possibilities.

⚙️

Algorithm

3 steps
  1. 1Step 1: Initialize a DP table where dp[l][r] represents the maximum operations possible for the subarray nums[l..r].
  2. 2Step 2: Iterate through all possible pairs of indices to calculate scores and update the DP table accordingly.
  3. 3Step 3: Use previously computed results to build up the solution for larger subarrays.
solution.py18 lines
1# Full working Python code
2
3def maxOperations(nums):
4    n = len(nums)
5    dp = [[0] * n for _ in range(n)]
6    for length in range(2, n + 1):
7        for l in range(n - length + 1):
8            r = l + length - 1
9            score1 = nums[l] + nums[l + 1]
10            score2 = nums[r] + nums[r - 1]
11            score3 = nums[l] + nums[r]
12            if score1 == score2:
13                dp[l][r] = max(dp[l][r], dp[l + 2][r] + 1)
14            if score1 == score3:
15                dp[l][r] = max(dp[l][r], dp[l + 1][r - 1] + 1)
16            if score2 == score3:
17                dp[l][r] = max(dp[l][r], dp[l][r - 2] + 1)
18    return dp[0][n - 1]

Complexity note: The complexity is O(n²) due to the nested loops for filling the DP table, but we use O(n²) space to store results for subarrays.

  • 1Understanding how to break down the problem into subproblems is crucial for dynamic programming.
  • 2Recognizing patterns in operations can lead to more efficient solutions.

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