-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathSolution798.cs
46 lines (40 loc) · 1.09 KB
/
Solution798.cs
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
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
namespace LeetCode.Solutions;
public class Solution798
{
/// <summary>
/// 798. Smallest Rotation with Highest Score - Hard
/// <a href="https://leetcode.com/problems/smallest-rotation-with-highest-score">See the problem</a>
/// </summary>
public int BestRotation(int[] nums)
{
int n = nums.Length;
int[] change = new int[n];
// Populate the change array
for (int i = 0; i < n; i++)
{
int low = (i + 1) % n;
int high = (i - nums[i] + n + 1) % n;
change[low]++;
change[high]--;
if (low > high)
{
change[0]++;
}
}
// Calculate the cumulative score for each rotation using the change array
int maxScore = -1;
int bestK = 0;
int currentScore = 0;
for (int k = 0; k < n; k++)
{
currentScore += change[k];
if (currentScore > maxScore)
{
maxScore = currentScore;
bestK = k;
}
}
return bestK;
}
}