Rotate Function (LeetCode 396): Solution and Explanation
Rotate nums right by k and score it as F(k) = sum of i * arr_k[i]. Return the largest score over all n rotations. For [4,3,2,6] the scores are 25, 16, 23 and 26, so the answer is 26.
Intuition
Computing every F(k) from scratch costs O(n) per rotation and O(n^2) overall, which is too slow for n = 10^5. The rotations are closely related, so look at what one more rotation changes.
Rotating right by one slides every value into the next slot, so its weight goes up by 1. If that happened to every value, F would grow by exactly sum(nums).
One value does not slide: the one in the last slot wraps to slot 0. Its weight drops from n - 1 to 0 instead of rising to n, so compared with the uniform +1 it loses n times its value.
That gives F(k) = F(k - 1) + sum - n * nums[n - k], an O(1) update. Compute F(0) once and walk through the rotations keeping the maximum.
Approach: Incremental rotation formula
- Compute
total = sum(nums)andF(0) = sum(i * nums[i]). - Set
best = F(0). - For
kfrom 1 ton - 1, updatef += total - n * nums[n - k]andbest = max(best, f). - Return
best.
Step-by-step example
nums = [4,3,2,6]
total = 15andF(0) = 0*4 + 1*3 + 2*2 + 3*6 = 25, sobest = 25.k = 1: 6 wraps to slot 0.F(1) = 25 + 15 - 4*6 = 16. best stays 25.k = 2: 2 wraps.F(2) = 16 + 15 - 4*2 = 23. best stays 25.k = 3: 3 wraps.F(3) = 23 + 15 - 4*3 = 26. best becomes 26, the answer.
Code: Python, Java, C++
1class Solution:
2 def maxRotateFunction(self, nums: List[int]) -> int:
3 n = len(nums)
4 total = sum(nums)
5 f = sum(i * x for i, x in enumerate(nums))
6 best = f
7 for k in range(1, n):
8 f += total - n * nums[n - k]
9 best = max(best, f)
10 return best1class Solution {
2 public int maxRotateFunction(int[] nums) {
3 int n = nums.length;
4 int total = 0, f = 0;
5 for (int i = 0; i < n; i++) {
6 total += nums[i];
7 f += i * nums[i];
8 }
9 int best = f;
10 for (int k = 1; k < n; k++) {
11 f += total - n * nums[n - k];
12 best = Math.max(best, f);
13 }
14 return best;
15 }
16}1class Solution {
2public:
3 int maxRotateFunction(vector<int>& nums) {
4 int n = nums.size();
5 int total = 0, f = 0;
6 for (int i = 0; i < n; i++) {
7 total += nums[i];
8 f += i * nums[i];
9 }
10 int best = f;
11 for (int k = 1; k < n; k++) {
12 f += total - n * nums[n - k];
13 best = max(best, f);
14 }
15 return best;
16 }
17};Time and space complexity
O(n)
One pass computes the sum and F(0); a second pass applies the O(1) update for each of the n - 1 rotations.
O(1)
Only the running F, the total and the best are kept.
Other approaches
Recompute each rotation (time O(n^2), space O(1))
For every k, build F(k) directly with a loop over the rotated indices (i - k) mod n. Simple and correct, but quadratic.
Left-rotation form (time O(n), space O(1))
Some solutions rotate the other way and use F(k) = F(k - 1) - total + n * nums[k - 1]. It visits the rotations in a different order but finds the same maximum.
Common mistakes
- Using the wrong wrapping element. Rotating right by k moves
nums[n - k]from the last slot to slot 0 at step k, notnums[k]. - Starting
bestat 0. With negative values every F can be negative, so initialisebestwith F(0). - Forgetting the n = 1 case. There is only F(0) = 0, and the loop must simply not run.
- Overflow in languages with fixed-width integers on larger inputs. The answer fits in 32 bits by the problem's guarantee; use 64-bit for intermediate values if you relax that.
Frequently asked questions
Why does every non-wrapping value add exactly its own value?
Its weight rises from i to i + 1, so its term grows by one copy of the value. Summing over all values gives total, and the wrapped one is then corrected.
Why subtract n times the wrapped value and not n - 1?
The + total already gave the wrapped value one extra unit of weight, as if it went to slot n. It actually goes to slot 0, so it must lose n units in total.
Is this a DP problem?
It is a one-variable recurrence: each F is the previous F plus a cheap correction. Keeping only the latest F is the space-optimised form of a DP table over k.