Skip to content

Commit 6c4037a

Browse files
committed
Add solution #798
1 parent 9004d8d commit 6c4037a

File tree

2 files changed

+52
-0
lines changed

2 files changed

+52
-0
lines changed

README.md

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -608,6 +608,7 @@
608608
795|[Number of Subarrays with Bounded Maximum](./0795-number-of-subarrays-with-bounded-maximum.js)|Medium|
609609
796|[Rotate String](./0796-rotate-string.js)|Easy|
610610
797|[All Paths From Source to Target](./0797-all-paths-from-source-to-target.js)|Medium|
611+
798|[Smallest Rotation with Highest Score](./0798-smallest-rotation-with-highest-score.js)|Hard|
611612
802|[Find Eventual Safe States](./0802-find-eventual-safe-states.js)|Medium|
612613
804|[Unique Morse Code Words](./0804-unique-morse-code-words.js)|Easy|
613614
819|[Most Common Word](./0819-most-common-word.js)|Easy|
Lines changed: 51 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,51 @@
1+
/**
2+
* 798. Smallest Rotation with Highest Score
3+
* https://leetcode.com/problems/smallest-rotation-with-highest-score/
4+
* Difficulty: Hard
5+
*
6+
* You are given an array nums. You can rotate it by a non-negative integer k so that the array
7+
* becomes [nums[k], nums[k + 1], ... nums[nums.length - 1], nums[0], nums[1], ..., nums[k-1]].
8+
* Afterward, any entries that are less than or equal to their index are worth one point.
9+
*
10+
* For example, if we have nums = [2,4,1,3,0], and we rotate by k = 2, it becomes [1,3,0,2,4].
11+
* This is worth 3 points because 1 > 0 [no points], 3 > 1 [no points], 0 <= 2 [one point],
12+
* 2 <= 3 [one point], 4 <= 4 [one point].
13+
*
14+
* Return the rotation index k that corresponds to the highest score we can achieve if we rotated
15+
* nums by it. If there are multiple answers, return the smallest such index k.
16+
*/
17+
18+
/**
19+
* @param {number[]} nums
20+
* @return {number}
21+
*/
22+
var bestRotation = function(nums) {
23+
const n = nums.length;
24+
const changes = new Array(n).fill(0);
25+
26+
for (let i = 0; i < n; i++) {
27+
const lowIndex = (i + 1) % n;
28+
const highIndex = (i - nums[i] + 1 + n) % n;
29+
30+
changes[lowIndex]++;
31+
changes[highIndex]--;
32+
33+
if (lowIndex > highIndex) {
34+
changes[0]++;
35+
}
36+
}
37+
38+
let maxScore = 0;
39+
let maxIndex = 0;
40+
let currentScore = 0;
41+
42+
for (let i = 0; i < n; i++) {
43+
currentScore += changes[i];
44+
if (currentScore > maxScore) {
45+
maxScore = currentScore;
46+
maxIndex = i;
47+
}
48+
}
49+
50+
return maxIndex;
51+
};

0 commit comments

Comments
 (0)