leetcode-daily/cpp/2203/220309-CN.cpp

47 lines
1.5 KiB
C++

#include <vector>
#include <cstring>
#include <iostream>
/**
* 798. Smallest Rotation with Highest Score
* 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.
*/
class Solution {
public:
static int bestRotation(const std::vector<int>& nums) {
int n = nums.size(), rotates[n];
std::memset(rotates, 0, sizeof rotates);
for (int i = 0; i < n; ++i)
if (nums[i] < n)
++rotates[(i - nums[i] + 1 + n) % n];
int ret = 0, retMax = 0;
for (int i = 0; i < n; ++i)
if (nums[i] <= i)
++retMax;
int now = retMax;
for (int i = 1; i <= n; ++i) {
// i -> i + 1
now -= rotates[i % n];
if (nums[i - 1] < n)
++now;
if (now > retMax) {
retMax = now;
ret = i;
}
}
return ret % n;
}
};
int main() {
std::cout << Solution::bestRotation({2,3,1,4,0}) << "\n";
std::cout << Solution::bestRotation({1,3,0,2,4});
return 0;
}