Smallest Rotation with Highest Score - Problem
You are given an array nums. You can rotate it by a non-negative integer k so that the array becomes [nums[k], nums[k + 1], ... nums[nums.length - 1], nums[0], nums[1], ..., nums[k-1]].
Afterward, any entries that are less than or equal to their index are worth one point.
For example, if we have nums = [2,4,1,3,0], and we rotate by k = 2, it becomes [1,3,0,2,4]. This is worth 3 points because:
1 > 0[no points]3 > 1[no points]0 ≤ 2[one point]2 ≤ 3[one point]4 ≤ 4[one point]
Return the rotation index k that corresponds to the highest score we can achieve if we rotated nums by it. If there are multiple answers, return the smallest such index k.
Input & Output
Example 1 — Basic Rotation
$
Input:
nums = [2,4,1,3,0]
›
Output:
3
💡 Note:
Rotating by k=3 gives [3,0,2,4,1]. Score: 3>0 (no), 0≤1 (yes), 2≤2 (yes), 4>3 (no), 1≤4 (yes) = 3 points. This is optimal.
Example 2 — Multiple Optimal Solutions
$
Input:
nums = [1,3,0,2,4]
›
Output:
0
💡 Note:
No rotation needed. Score: 1>0 (no), 3>1 (no), 0≤2 (yes), 2≤3 (yes), 4≤4 (yes) = 3 points. This equals other rotations but k=0 is smallest.
Example 3 — Edge Case Small Array
$
Input:
nums = [1,1]
›
Output:
1
💡 Note:
k=0: [1,1] scores 1 point (1≤1). k=1: [1,1] scores 1 point (1≤1). Both equal, return k=1 since it's the only other option.
Constraints
- 1 ≤ nums.length ≤ 105
- 0 ≤ nums[i] < nums.length
Visualization
Tap to expand
Understanding the Visualization
1
Input
Array [2,4,1,3,0] - find best rotation k
2
Process
Try rotations and count nums[i] ≤ i conditions
3
Output
Return k=3 with maximum score
Key Takeaway
🎯 Key Insight: Track score changes as rotation increases instead of recalculating from scratch
💡
Explanation
AI Ready
💡 Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code