Setting up the recurrence
Let's derive the relationship between F(k - 1) and F(k) carefully. Take nums = [4, 3, 2, 6].
F(0) = 0·4 + 1·3 + 2·2 + 3·6 = 0 + 3 + 4 + 18 = 25
F(1) = 0·6 + 1·4 + 2·3 + 3·2 = 0 + 4 + 6 + 6 = 16
F(2) = 0·2 + 1·6 + 2·4 + 3·3 = 0 + 6 + 8 + 9 = 23
F(3) = 0·3 + 1·2 + 2·6 + 3·4 = 0 + 2 + 12 + 12 = 26 ← max
Compare F(0) and F(1) term-by-term. Going from rotation 0 to rotation 1, each element's index (its coefficient) shifts by +1:
4 was at index 0, now at index 1 — coefficient up by 1.
3 was at index 1, now at index 2 — up by 1.
2 was at index 2, now at index 3 — up by 1.
6 was at index 3, but it can't go to index 4 — it wraps around to index 0.
So three elements gained +1 to their coefficient (contributing + (4 + 3 + 2) to the total) and one element dropped from coefficient 3 to 0 (contributing - 3·6). That gives:
F(1) - F(0) = (4 + 3 + 2) - 3·6 = 9 - 18 = -9
F(1) = F(0) - 9 = 25 - 9 = 16 ✓
Cleaning the formula
Notice that (4 + 3 + 2) is just sum(nums) - 6, i.e. S - nums[n - 1]. Substituting:
F(1) - F(0) = (S - nums[n - 1]) - (n - 1) · nums[n - 1]
= S - n · nums[n - 1]
Generalising, the element that wraps to index 0 when going from F(k - 1) to F(k) is nums[n - k]. So:
F(k) = F(k - 1) + S - n · nums[n - k]
Steps
- Compute
S = sum(nums) and F = sum(i · nums[i]) (this is F(0)).
- Track
best = F.
- For
k = 1, 2, …, n - 1:
- Update
F += S - n · nums[n - k].
- Update
best = max(best, F).
- Return
best.
Walk-through
nums = [4, 3, 2, 6], n = 4, S = 15.
| k | wraps to 0 | F update | F | best |
|---|
| 0 | — | initial F(0) | 25 | 25 |
| 1 | nums[3]=6 | F += 15 - 4·6 = -9 | 16 | 25 |
| 2 | nums[2]=2 | F += 15 - 4·2 = 7 | 23 | 25 |
| 3 | nums[1]=3 | F += 15 - 4·3 = 3 | 26 | 26 |
Answer: 26.
Edge cases
- Single element: the loop never runs;
F(0) = 0. Correct.
- All zeros: every
F(k) equals 0.
- Negative values: the recurrence still holds — no special-case needed.
Complexity
- Time:
O(n) — one pass for S and F(0), one pass for the recurrence.
- Space:
O(1).