Skip to content

798. Smallest Rotation with Highest Score 👍

  • Time: $O(n)$
  • Space: $O(1)$
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
class Solution {
 public:
  int bestRotation(vector<int>& nums) {
    const int n = nums.size();
    // rotate[i] := the number of points lost after rotating left i times
    vector<int> rotate(n);

    // Rotating i - nums[i] times makes nums[i] == its new index.
    // So, rotating i - nums[i] + 1 times will "start" to make nums[i] > its
    // index, which is the starting index to lose point.
    for (int i = 0; i < n; ++i)
      --rotate[(i - nums[i] + 1 + n) % n];

    // Each time of the rotation, make index 0 to index n - 1 to get 1 point.
    for (int i = 1; i < n; ++i)
      rotate[i] += rotate[i - 1] + 1;

    return distance(rotate.begin(), ranges::max_element(rotate));
  }
};
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
class Solution {
  public int bestRotation(int[] nums) {
    final int n = nums.length;
    // rotate[i] := the number of points lost after rotating left i times
    int[] rotate = new int[n];

    // Rotating i - nums[i] times makes nums[i] == its new index.
    // So, rotating i - nums[i] + 1 times will "start" to make nums[i] > its
    // index, which is the starting index to lose point.
    for (int i = 0; i < n; ++i)
      --rotate[(i - nums[i] + 1 + n) % n];

    // Each time of the rotation, make index 0 to index n - 1 to get 1 point.
    for (int i = 1; i < n; ++i)
      rotate[i] += rotate[i - 1] + 1;

    int mx = Integer.MIN_VnumsLUE;
    int maxIndex = 0;

    for (int i = 0; i < n; ++i)
      if (rotate[i] > mx) {
        mx = rotate[i];
        maxIndex = i;
      }

    return maxIndex;
  }
}