MediumNo. 0396

Rotate Function — LeetCode 396 Python Solution

Topics
Array, Math, Dynamic Programming
Reading time
2 min

The problem

You are given an integer array nums of length n. Assume arrk to be an array obtained by rotating nums by k positions clock-wise.

Example

Input
nums = [4,3,2,6]
Output
26
Explanation
F(0) = (0 * 4) + (1 * 3) + (2 * 2) + (3 * 6) = 0 + 3 + 4 + 18 = 25

Python solution

PythonSolution
class Solution:
    def maxRotateFunction(self, nums: List[int]) -> int:
        f = sum(i * v for i, v in enumerate(nums))
        n, s = len(nums), sum(nums)
        ans = f
        for i in range(1, n):
            f = f + s - n * nums[n - i]
            ans = max(ans, f)
        return ans

Complexity

Time
O(n·m) (typical)
Space · auxiliary
O(n·m)or optimized

Pattern: Dynamic Programming

Define a state, write the transition, and stop recomputing the same subproblem. LeetCode 396. Rotate Function is filed here on both counts: the reference solution below belongs to the algorithm family this hub collects, and LeetCode tags it Dynamic Programming.

The dynamic programming guide has the Python template for the pattern and the 481 LeetCode problems that use it.

Related problems

Related problems
No.ProblemDifficulty
0313Super Ugly NumberMedium
0368Largest Divisible SubsetMedium
0486Predict the WinnerMedium
0553Optimal DivisionMedium
0805Split Array With Same AverageHard
0877Stone GameMedium

Frequently asked questions

How hard is LeetCode 396. Rotate Function?

LeetCode 396. Rotate Function is rated Medium on LeetCode.

What topics does LeetCode 396. Rotate Function cover?

LeetCode 396. Rotate Function is tagged Array, Math and Dynamic Programming on LeetCode.

Stuck on problems like this in a live interview?

Stealth Interview is a desktop app for macOS and Windows. It reads the problem off your screen and returns a working solution with a step-by-step explanation and its time and space complexity, invisible to screen sharing.

Free to download. Check it runs on your machine, then pick a plan.