Skip to content
Problem 396 · LeetCode 396(opens in a new tab)

Rotate Function

MediumArrays

You get an array nums of length n. Turning it right by k places moves every value k positions to the right, and values that fall off the end wrap round to the front. Call the turned array arr.

For each k from 0 to n − 1, define F(k) = 0·arr[0] + 1·arr[1] + ... + (n − 1)·arr[n − 1]: each value times its position. Return the largest F(k).

Example 1

Input:  nums = [2, 5, 1, 3]
Output: 22
Why:    F(0..3) = 16, 15, 22, 13; turned twice it is [1, 3, 2, 5]
2 more examples and the constraints

Example 2

Input:  nums = [-7]
Output: 0
Why:    one value always sits at position 0

Example 3

Input:  nums = [4, -2]
Output: 4
Why:    F(0) = 0·4 + 1·(−2) = −2, F(1) = 0·(−2) + 1·4 = 4

Constraints

  • 1 ≤ n ≤ 100,000
  • −100 ≤ nums[i] ≤ 100
  • The answer fits in a signed 32-bit integer

Your turn first

Have a go on paper or in your own editor, then reveal the approaches from the simplest up.

Try it on LeetCode(opens in a new tab)
  1. Compute every F(k)O(n²)
  2. One turn at a timeO(n)

The idea in one sentence

The pattern, how to spot it, and the best complexity.

Side by side

ApproachTimeRelative work for 100,000 valuesVerdict
Compute every F(k)O(n²)
Too slow at n = 100,000
One turn at a timeO(n)
Best; one pass

n = length of nums.

Edge cases to test

  • One value. [−7] gives 0: the only value always has weight 0.
  • All negative. Every F can be negative, so do not start best at 0; start it at F(0).
  • All equal. Every rotation gives the same F; the recurrence adds total − n·x = 0 each time.
  • Large n. Intermediate F values can pass the 32-bit limit, so use 64-bit sums.

Common mistakes

  • Starting best at 0, which is wrong when every F(k) is negative.
  • Using nums[k − 1] instead of nums[n − k]: turning right moves the last value to the front, not the first.
  • Building each rotated array, which is O(n²) time and extra memory.

How to talk through it

  1. 1Clarify. Which way does the array turn? Can values be negative? Does the answer fit in 32 bits?
  2. 2Give the brute force. Compute every F(k) directly: O(n²), too slow for 100,000.
  3. 3Find the link. One more turn adds the total and takes n times the wrapped value: F(k) = F(k − 1) + total − n·nums[n − k].
  4. 4Code the pass. Compute F(0) and the total, then apply the recurrence n − 1 times, keeping the max.
  5. 5Test out loud. Check Example 1 by hand, then a single value and an all-negative array.
Was this problem useful?Your vote tells us what to improve next.
Found a bug in our code, or something unclear?