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 byk = 2
, it becomes[1,3,0,2,4]
. This is worth3
points because1 > 0
[no points],3 > 1
[no points],0 <= 2
[one point],2 <= 3
[one point],4 <= 4
[one point].
Return the rotation indexk
that corresponds to the highest score we can achieve if we rotatednums
by it. If there are multiple answers, return the smallest such index k
.
Examples
Example 1
|
|
Example 2
|
|
Constraints
1 <= nums.length <= 10^5
0 <= nums[i] < nums.length
Solution
Method 1 – Difference Array and Prefix Sum
Intuition
For each index, we can determine the range of rotations where it contributes a point. Using a difference array, we can efficiently accumulate the score changes for all rotations, then use prefix sum to get the score for each rotation.
Approach
- For each index i, calculate the range of k where nums[i] <= (i - k + n) % n.
- For each such range, increment the score at the start and decrement after the end in a difference array.
- Compute the prefix sum to get the score for each rotation.
- Return the smallest k with the highest score.
Code
|
|
|
|
|
|
|
|
|
|
|
|
|
|
Complexity
- ⏰ Time complexity:
O(n)
, where n is the length of nums. Each index is processed a constant number of times. - 🧺 Space complexity:
O(n)
, for the difference array.