#1770
Maximum Score from Performing Multiplication Operations
HardArrayDynamic ProgrammingDynamic ProgrammingRecursion
Approaches
Brute ForceOptimal
Complexity Comparison
| Brute Force | Optimal Solution★ | |
|---|---|---|
| Time | O(n²) | O(m²) |
| Space | O(1) | O(m) |
💡
Intuition
Time O(m²)Space O(m)
The optimal solution uses dynamic programming to store results of subproblems, avoiding redundant calculations. By using a DP table, we can efficiently compute the maximum score by building on previously computed results.
⚙️
Algorithm
3 steps- 1Step 1: Initialize a DP table with dimensions (m+1) x (m+1) to store maximum scores for different choices.
- 2Step 2: Iterate through the multipliers in reverse order, calculating the maximum score for each possible left choice.
- 3Step 3: For each multiplier, update the DP table based on choosing from the left or right end of nums.
solution.py8 lines
1def maximumScore(nums, multipliers):
2 m = len(multipliers)
3 dp = [[0] * (m + 1) for _ in range(m + 1)]
4 for i in range(m - 1, -1, -1):
5 for left in range(i + 1):
6 right = m - 1 - i + left
7 dp[i][left] = max(multipliers[i] * nums[left] + dp[i + 1][left + 1], multipliers[i] * nums[right] + dp[i + 1][left])
8 return dp[0][0]ℹ
Complexity note: The time complexity is O(m²) because we fill an m x m DP table, where m is the number of multipliers. The space complexity is O(m) for the DP table.
- 1Choosing from both ends of the array can lead to different scores based on future multipliers.
- 2Dynamic programming helps avoid recalculating scores for the same state.
Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.