Rotate Function — LeetCode 396 Python Solution

MediumArrayMathDynamic Programming
Problem
#396
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

Python
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

MeasureComplexity
TimeO(n·m) (typical)
SpaceO(n·m) or optimized auxiliary

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

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.

Get Stealth Interview