Problem 396

Abstract / Summary

Given an array compute the maximum sum obtained by rotating it and multiplying each element by its index.

Note

The full problem description, including helpful examples, can be found on LeetCode.

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
16 lines | 465 bytes | submitted October 3, 2023 | GitHub   18% comment ratio | tab size 4 | low complexity

Difficulty

This problem is ranked as
easy medium hard

and has an acceptance rate of about 54% (300k+ submissions).

Typical patterns to solve this problem:
  • Array
  • Dynamic Programming
  • Math
I solved 663 easy, 1250 medium and 309 hard problems

AI Disclaimer

Every single line of code was written by me, 100% from scratch, between August 2023 and August 2024.
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.
LeetCode profile | GitHub repo

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.

written by openai gpt

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.

written by google gemini

Code Quality

Several LLMs ranked my code quality on a scale from 1 (very poor) to 10 (outstanding):
n = 26 | median = 8.5 | μ = 8.38 | σ = 0.79

Complexity Analysis

Time: linear
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
generated automatically

Other Solutions

I wrote a basic crawler to find other solutions to that problem.
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++
34 links | 20 authors | 8 languages

Videos

5 videos   did my crawler come up with invalid videos ? drop me a line.

Solved On The Same Day

6 easy 3 medium 4 hard
14 solutions   October 3, 2023

Extra

There are a few extra pages giving you some insights into my setup:
  • 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