#798
Smallest Rotation with Highest Score
candidate master · 1340 · lc hard +32 · verified · 53.5% accepted · 564 likes · top 45%
Description
You are given an array nums. Rotating it by a non-negative integer k produces [nums[k], nums[k + 1], ..., nums[nums.length - 1], nums[0], nums[1], ..., nums[k-1]]. After rotating, each element that is less than or equal to its new index earns one point.
- For example, rotating nums = [2,4,1,3,0] by k = 2 gives [1,3,0,2,4], which earns 3 points because 0 <= 2, 2 <= 3, and 4 <= 4.
Return the rotation value k that yields the maximum score. If multiple values of k give the same top score, return the smallest such k.
Example 1:
Input: nums = [2,3,1,4,0]
Output: 3
Explanation: Scores for each k are listed below:
k = 0, nums = [2,3,1,4,0], score 2
k = 1, nums = [3,1,4,0,2], score 3
k = 2, nums = [1,4,0,2,3], score 3
k = 3, nums = [4,0,2,3,1], score 4
k = 4, nums = [0,2,3,1,4], score 3
So we should choose k = 3, which has the highest score.
Example 2:
Input: nums = [1,3,0,2,4]
Output: 0
Explanation: nums will always have 3 points no matter how it shifts.
So we will choose the smallest k, which is 0.
Code
1
2
3