#3290

Maximum Multiplication Score

Medium
ArrayDynamic ProgrammingDynamic ProgrammingGreedy Algorithms
LeetCode ↗

Approaches

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

Intuition

Time O(n)Space O(1)

The optimal solution uses dynamic programming to build the maximum score incrementally. By maintaining an array that tracks the best scores for selecting up to 4 indices, we can efficiently calculate the maximum score without checking all combinations.

⚙️

Algorithm

4 steps
  1. 1Step 1: Initialize a DP array of size 5 (for 0 to 4 selections) with negative infinity.
  2. 2Step 2: Iterate through each element in b, updating the DP array for each selection count (from 4 down to 1).
  3. 3Step 3: For each element in b, calculate the potential new scores and update the DP array accordingly.
  4. 4Step 4: The maximum score will be found in DP[4] after processing all elements in b.
solution.py9 lines
1# Full working Python code
2
3def maxMultiplicationScore(a, b):
4    dp = [-float('inf')] * 5
5    dp[0] = 0
6    for num in b:
7        for j in range(4, 0, -1):
8            dp[j] = max(dp[j], dp[j-1] + a[j-1] * num)
9    return dp[4]

Complexity note: The time complexity is O(n) because we iterate through the array b once and update the DP array in constant time. The space complexity is O(1) since we only use a fixed-size DP array.

  • 1Dynamic programming allows us to build solutions incrementally, avoiding the need to check all combinations.
  • 2Understanding how to maintain state in a DP array is crucial for optimizing problems involving selections.

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