Python 0396.py
class Solution:
def maxRotateFunction(self, nums: List[int]) -> int:
total = sum(nums)
# F(0)
initial = 0
for i, n in enumerate(nums):
initial += i * n
# F(n) = F(n-1) + sum(nums) - len(nums) * nums[n]
best = current = initial
for i in range(len(nums) - 1, 0, -1):
current += total - len(nums) * nums[i]
best = max(best, current)
return best
Difficulty
and has an acceptance rate of about 54% (300k+ submissions).
Typical patterns to solve this problem:
- Array
- Dynamic Programming
- Math
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 computes the maximum value of the rotation function defined for an integer array. The rotation function F(k) is the weighted sum of array elements after rotating the array k positions to the right. The algorithm leverages a mathematical recurrence to evaluate all possible rotations in linear time, avoiding the need to rebuild the array for each rotation.
Key Steps
Computing the total sum of the array
The first operation aggregates all elements of the input list. This aggregate value is reused in the recurrence relation, eliminating repeated summations.
total = sum(nums)
Calculating the initial rotation value F(0)
The algorithm determines the base case F(0) by iterating over the original array and accumulating the product of each element with its index. This establishes the starting point for the recurrence.
initial = 0
for i, n in enumerate(nums):
initial += i * n
Iterating through rotations using the recurrence
The core of the solution is a reverse loop that updates the current rotation value based on the previously computed value. The recurrence F(k) = F(k-1) + total - n · nums[n-k] is applied, where n is the length of the array. By traversing the indices from the end toward the beginning, each step efficiently derives the next rotation value without explicit array manipulation.
best = current = initial
for i in range(len(nums) - 1, 0, -1):
current += total - len(nums) * nums[i]
best = max(best, current)
Returning the maximum rotation value
After processing all possible rotations, the algorithm returns the highest value encountered.
return best
Edge Cases Handled
When the input list contains a single element, the total sum equals that element, and the initial weighted sum is zero because the only index is 0. The loop that updates rotations runs zero times, leaving best equal to initial, which correctly represents the only possible rotation value.
If the list is empty, the built-in sum function returns 0, and the enumeration loop produces no iterations, leaving initial at 0. The subsequent loop also performs no iterations, and the function returns 0, which is a sensible default for an undefined rotation function on an empty collection.
The algorithm also gracefully handles arrays with negative numbers. The total sum and weighted sums incorporate sign information directly, and the recurrence correctly propagates these values, ensuring that the maximum across all rotations reflects the true optimum even when intermediate results are negative.
Performance Optimizations
The solution avoids constructing rotated copies of the array, which would incur O(n²) time. Instead, it uses a constant-time update formula that reuses the previously computed rotation value, the pre-computed total sum, and the length of the array. This reduces the overall work to a single pass for the initial weighted sum and a second linear pass for the recurrence, yielding a linear-time algorithm.
By storing the length of the array in a local variable within the loop condition, the code prevents repeated attribute lookups, which can be a minor but measurable overhead in tight loops. The use of a single variable current to hold the evolving rotation value eliminates the need for an auxiliary array to keep intermediate results, thereby conserving memory and improving cache locality.
The final comparison best = max(best, current) updates the optimum in place, avoiding an additional pass to locate the maximum after all rotations have been processed. This in-place tracking contributes to the overall efficiency of the implementation.
ELI5 - Simplified Explanation
Imagine a line of numbered toy blocks sitting on the floor. Each block has a special value written on it, and each spot on the floor has a number too. To find a score, you multiply the number on each block by the number on the spot where it is sitting, and then you add all those scores together.
The code starts by figuring out what the total would be if the blocks stayed exactly where they are right now. It does this by checking each block one by one and doing the math.
After that, the code plays a game where it spins the line of blocks around. Imagine sliding the last block to the very front of the line, which pushes all the other blocks one spot to the right. When the blocks move, the math changes, but in a very clever way. Instead of starting the math over from scratch, the code uses a shortcut. It takes the score it just had, adds the total of all the blocks, and then subtracts a special amount based on the block that just moved to the front.
As the blocks keep spinning, the code watches to see which turn gives the highest score. It keeps track of the biggest score it has seen so far and saves that as the best result. By the time the blocks have finished spinning all the way around, the largest score found is chosen.
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 | Rust | Python | Go | TS | |||
| LeetcodeHelp | C++ | Java | Python | ||||||
| Progiez | C++ | Java | Python | ||||||
| github | black-shadows | C++ | |||||||
| charles-wangkai | Java | ||||||||
| everthis | JS | ||||||||
| fsq | C++ | ||||||||
| gouthampradhan | Java | ||||||||
| halfrost | Go | ||||||||
| haoel | C++ | ||||||||
| JoshCrozier | JS | ||||||||
| linouk23 | C++ | ||||||||
| lkwq007 | Python | ||||||||
| lzl124631x | C++ | ||||||||
| ruoru | Rust | ||||||||
| suxrobGM | C# | ||||||||
| varunu28 | Java | ||||||||
| withaarzoo | C++ | ||||||||
| AlgoMonster | C++, Python, Java, TypeScript | ||||||||
| WalkCCC | C++, Python, Java | ||||||||
| leetcode.ca | C++, Go, Java, Python, Rust, TypeScript | ||||||||
| LeetcodeHelp | C++, Java, Python | ||||||||
| Progiez | C++, Java, Python | ||||||||
| black-shadows | C++, C++ | ||||||||
| charles-wangkai | Java | ||||||||
| everthis | JavaScript | ||||||||
| fsq | C++ | ||||||||
| gouthampradhan | Java | ||||||||
| halfrost | Go | ||||||||
| haoel | C++ | ||||||||
| JoshCrozier | JavaScript | ||||||||
| linouk23 | C++ | ||||||||
| lkwq007 | Python | ||||||||
| lzl124631x | C++ | ||||||||
| ruoru | Rust | ||||||||
| suxrobGM | C# | ||||||||
| varunu28 | Java | ||||||||
| withaarzoo | C++ |
Videos
Solved On The Same Day
- problem 598: Range Addition II
- problem 653: Two Sum IV - Input is a BST
- problem 1470: Shuffle the Array
- problem 1512: Number of Good Pairs
- problem 1920: Build Array from Permutation
- problem 1929: Concatenation of Array
- problem 877: Stone Game
- problem 1033: Moving Stones Until Consecutive
- problem 2396: Strictly Palindromic Number
- problem 1402: Reducing Dishes
- problem 1406: Stone Game III
- problem 1463: Cherry Pickup II
- problem 1510: Stone Game IV
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