Python 1770.py
class Solution:
def maximumScore(self, nums: List[int], multipliers: List[int]) -> int:
@cache
def deeper(left, right): # numbers already removed on the left and right side of nums
m = left + right
if m == len(multipliers):
return 0
a = multipliers[m] * nums[left] + deeper(left + 1, right)
b = multipliers[m] * nums[-(right + 1)] + deeper(left, right + 1)
return max(a, b)
return deeper(0, 0)
Difficulty
and has an acceptance rate of about 44% (300k+ submissions).
Typical patterns to solve this problem:
- Array
- Dynamic Programming
AI Disclaimer
However, two years later I set up this website and used various AI tools to generate most of the walkthrough / explanations below.
See this dedicated page for more details.
Code Walkthrough
Overview
The provided implementation defines a Solution class with a single public method maximumScore. The method receives two integer lists: nums, the original array of values, and multipliers, a shorter list that determines how many operations will be performed. The algorithm selects elements from either the leftmost or rightmost end of nums for each multiplier, multiplies them, and accumulates the result. The goal is to maximize the total score after all multipliers have been applied.
The core of the solution is a depth-first recursion that explores both choices at each step-taking from the left side or the right side. Memoization, applied via the @cache decorator, eliminates redundant recomputation of sub-problems, turning the exponential search space into a tractable dynamic programming solution.
Key Steps
Entry Point
The public method initializes the recursive process with zero elements removed from either side of nums.
return deeper(0, 0)
Recursive Definition
A nested function deeper is declared inside maximumScore. It receives two integer arguments, left and right, representing how many elements have already been taken from the left and right ends of nums, respectively.
@cache
def deeper(left, right):
m = left + right
if m == len(multipliers):
return 0
...
The variable m denotes the current operation index, derived from the total number of elements already removed. When m reaches the length of multipliers, the recursion terminates, returning a base score of zero because no further multiplications are possible.
Choice Evaluation
Two candidate scores are computed for the current operation.
The first candidate, a, corresponds to selecting the leftmost remaining element. The element is accessed directly via nums[left], multiplied by the current multiplier, and the recursion proceeds with left incremented.
a = multipliers[m] * nums[left] + deeper(left + 1, right)
The second candidate, b, corresponds to selecting the rightmost remaining element. The rightmost element is accessed using a negative index that accounts for how many elements have already been removed from the right side (right). The recursion proceeds with right incremented.
b = multipliers[m] * nums[-(right + 1)] + deeper(left, right + 1)
The function returns the larger of the two candidates, ensuring that the optimal decision is propagated upward through the call stack.
return max(a, b)
Edge Cases Handled
When the number of multipliers equals zero, the base case if m == len(multipliers): return 0 is triggered immediately, and the method returns a score of zero without accessing any elements of nums.
If nums contains a single element and multipliers also contains a single element, the recursion evaluates both left and right choices, which both reference the same element due to the symmetric indexing. The max operation correctly selects the only possible score.
When all multipliers have been consumed but some elements of nums remain untouched, the recursion stops at the base case, ignoring the leftover elements, which aligns with the problem definition that only a fixed number of operations are performed.
The negative indexing used for the right side (nums[-(right + 1)]) gracefully handles the situation where right reaches the length of nums minus the number of left removals, because Python raises an IndexError only when the index exceeds the bounds. The recursion never reaches an invalid state because the termination condition is based on the length of multipliers, which is guaranteed to be less than or equal to the length of nums.
Performance Optimizations
The most significant optimization is the use of the @cache decorator from the functools module. By caching the results of each (left, right) pair, the algorithm avoids recomputing identical sub-problems that arise from different decision paths converging to the same state. This memoization transforms the naive exponential recursion into a dynamic programming solution with a number of distinct states bounded by the product of the possible left and right removal counts.
Another subtle optimization is the avoidance of slicing or copying nums. The algorithm works directly with index offsets (left and right) to reference the required elements, thereby keeping memory usage low and preventing the overhead associated with creating new list objects at each recursive step.
The recursion depth is limited by the length of multipliers. Since each recursive call consumes exactly one multiplier, the maximum depth equals the number of operations, which is typically much smaller than the length of nums. This bounded depth ensures that the call stack remains manageable and that Python’s recursion limit is unlikely to be reached for typical input sizes.
By combining memoization with index-based element access, the implementation achieves a highly efficient exploration of the decision space while maintaining clear and concise code structure.
ELI5 - Simplified Explanation
Imagine a row of number cards lying on a table in front of you. A game gives you a set of special multiplier cards to use one by one. Each turn, you have to pick a multiplier card and use it to multiply either the number card at the very far left end or the number card at the very far right end of your main row. Once you pick a card from the row, it disappears, and you keep going until all the multiplier cards are used up.
The code is like a clever helper that looks ahead to see every possible way to play this game. The helper spots the current multiplier card and tests what happens if you pick the left side versus what happens if you pick the right side. Because the game can get very complicated with many cards, the helper remembers the answers to positions it has already figured out so that it does not have to do the same work again. It keeps bouncing back and forth between the two sides, making the best choice at every step until every multiplier card has been used, aiming to leave you with the biggest possible result at the end.
Code Quality
Complexity Analysis
As a rule of thumb, the maximum input size for one second execution time is
- factorial: up to 10 elements
- exponential: up to 20 elements
- polynomial: a few thousand elements
- loglinear: up to 100,000 elements
- linear: a few million elements
- logarithmic: a billion elements
- constant: practically unlimited
Other Solutions
Obviously, I did that after I solved the problem myself.
In general, AlgoMonster and WalkCCC solutions are high-quality and always worth a look.
I haven't checked most of the other solutions, but they might be helpful as well.
And of course, the LeetCode forum is always a good place (or even the best) to look for alternative approaches.
(click on a column header to sort the table)
| author | |||||||||
|---|---|---|---|---|---|---|---|---|---|
| author | solutions | ||||||||
| www | AlgoMonster | C++ | Java | Python | TS | ||||
| WalkCCC | C++ | Java | Python | ||||||
| leetcode.ca | C++ | Java | Python | Go | TS | ||||
| Progiez | C++ | Java | Python | ||||||
| github | black-shadows | C++ | |||||||
| charles-wangkai | Java | ||||||||
| everthis | JS | ||||||||
| fartem | Ruby | ||||||||
| fsq | C++ | ||||||||
| haoel | C++ | ||||||||
| JoshCrozier | JS | ||||||||
| lkwq007 | Python | ||||||||
| suxrobGM | C# | ||||||||
| varunu28 | Java | ||||||||
| vthwang | Java | ||||||||
| wisdompeak | C++ | ||||||||
| AlgoMonster | C++, Python, Java, TypeScript | ||||||||
| WalkCCC | C++, Python, Java | ||||||||
| leetcode.ca | C++, Go, Java, Python, TypeScript | ||||||||
| Progiez | C++, Java, Python | ||||||||
| black-shadows | C++, C++ | ||||||||
| charles-wangkai | Java | ||||||||
| everthis | JavaScript | ||||||||
| fartem | Ruby | ||||||||
| fsq | C++ | ||||||||
| haoel | C++ | ||||||||
| JoshCrozier | JavaScript | ||||||||
| lkwq007 | Python | ||||||||
| suxrobGM | C# | ||||||||
| varunu28 | Java | ||||||||
| vthwang | Java | ||||||||
| wisdompeak | C++ |
Videos
Similar Problems
- problem 1690: Stone Game VII
- problem 2931: Maximum Spending After Buying Items
Solved On The Same Day
- problem 1800: Maximum Ascending Subarray Sum
- problem 1837: Sum of Digits in Base K
- problem 1813: Sentence Similarity III
- problem 1824: Minimum Sideway Jumps
Extra
- Tech Stack - my development environment and tools
- AI - how AI helped me create this website (NOT solving the problems)
- Progress - progression over time
- Quality - code quality