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
Rotate Function - Optimal Solution INPUT Array nums[] 4 i=0 3 i=1 2 i=2 6 i=3 F(0) Calculation: 0*4 + 1*3 + 2*2 + 3*6 = 0 + 3 + 4 + 18 = 25 Sum = 4+3+2+6 = 15 n = 4 Clockwise Rotation: [4,3,2,6] --> [6,4,3,2] [6,4,3,2] --> [2,6,4,3] [2,6,4,3] --> [3,2,6,4] ALGORITHM STEPS 1 Calculate F(0) and Sum F(0)=25, Sum=15 2 Use Recurrence Formula F(k) = F(k-1) + Sum - n*arr[n-k] 3 Compute All F(k) Iterate k from 1 to n-1 4 Track Maximum Update max at each step Calculations: F(0) = 25 F(1) = 25+15-4*6 = 16 F(2) = 16+15-4*2 = 23 F(3) = 23+15-4*3 = 26 MAX! FINAL RESULT All F(k) Values: F(0) 25 F(1) 16 F(2) 23 F(3) 26 Maximum Value 26 Output: 26 [OK] Maximum found at k=3 Key Insight: Instead of recalculating F(k) from scratch (O(n) each), use the recurrence relation: F(k) = F(k-1) + Sum - n * nums[n-k] This gives O(n) time complexity instead of O(n^2). Each rotation shifts indices by 1. TutorialsPoint - Rotate Function | Optimal Solution O(n)
Asked in
Google 15 Amazon 12 Microsoft 8
23.4K Views
Medium Frequency
~25 min Avg. Time
892 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen