Rotate Function - Problem
You are given an integer array nums of length n. Assume arr_k to be an array obtained by rotating nums by k positions clock-wise.
We define the rotation function F on nums as follow:
F(k) = 0 * arr_k[0] + 1 * arr_k[1] + ... + (n - 1) * arr_k[n - 1]
Return the maximum value of F(0), F(1), ..., F(n-1).
The test cases are generated so that the answer fits in a 32-bit integer.
Input & Output
Example 1 — Basic Case
$
Input:
nums = [4,3,2,6]
›
Output:
26
💡 Note:
F(0) = 0×4+1×3+2×2+3×6 = 25, F(1) = 0×3+1×2+2×6+3×4 = 26, F(2) = 0×2+1×6+2×4+3×3 = 23, F(3) = 0×6+1×4+2×3+3×2 = 16. Maximum is F(1) = 26.
Example 2 — Single Element
$
Input:
nums = [100]
›
Output:
0
💡 Note:
Only one rotation possible: F(0) = 0×100 = 0
Example 3 — All Same Elements
$
Input:
nums = [1,1,1,1]
›
Output:
6
💡 Note:
All rotations give same result: F(0) = 0×1+1×1+2×1+3×1 = 6
Constraints
- 1 ≤ nums.length ≤ 105
- -100 ≤ nums[i] ≤ 100
Visualization
Tap to expand
Understanding the Visualization
1
Input Array
nums = [4,3,2,6] with positions 0,1,2,3
2
Calculate F(k)
For each rotation k, compute weighted sum
3
Find Maximum
Return the largest F(k) value across all rotations
Key Takeaway
🎯 Key Insight: Use mathematical relationship F(k+1) = F(k) + sum - n×nums[n-k-1] to avoid recalculating each rotation
💡
Explanation
AI Ready
💡 Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code