LeetCode每日一题(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.

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.

Constraints:

  • 1 <= nums.length <= 105
  • 0 <= nums[i] < nums.length

旋转的 num 个数从 0 到 nums.len() - 1

假设 scores[i]为旋转 i 个 nums 后所能得到的 score

我们统计每个 num 对 scores[i]所做的贡献



impl Solution {
    pub fn best_rotation(nums: Vec<i32>) -> i32 {
        let length = nums.len();
        let mut trands = vec![0; nums.len() + 1];
        for (i, v) in nums.into_iter().enumerate() {
            if v <= i as i32 {
                trands[0] += 1;
                trands[i - v as usize + 1] -= 1;
                trands[i + 1] += 1;
                continue;
            }
            trands[i + 1] += 1;
            trands[length - (v as usize - i) + 1] -= 1;
        }
        let mut score = 0;
        let mut curr = 0;
        let mut ans = 0;
        for (i, v) in trands.into_iter().enumerate() {
            curr += v;
            if curr > score {
                score = curr;
                ans = i;
            }
        }
        ans as i32
    }
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值