LeetCode 题解工作台

旋转函数

给定一个长度为 n 的整数数组 nums 。 假设 arr k 是数组 nums 顺时针旋转 k 个位置后的数组,我们定义 nums 的 旋转函数 F 为: F(k) = 0 * arr k [0] + 1 * arr k [1] + ... + (n - 1) * arr k [n - 1] 返回…

category

3

题型

code_blocks

6

代码语言

hub

3

相关题

当前训练重点

中等 · 状态·转移·动态规划

bolt

答案摘要

class Solution: def maxRotateFunction(self, nums: List[int]) -> int:

Interview AiBox logo

Interview AiBox 实时 AI 助手,陪你讲清 状态·转移·动态规划 题型思路

试试 AiBox 面试助手arrow_forward
description

题目描述

给定一个长度为 n 的整数数组 nums 。

假设 arrk 是数组 nums 顺时针旋转 k 个位置后的数组,我们定义 nums 的 旋转函数  F 为:

  • F(k) = 0 * arrk[0] + 1 * arrk[1] + ... + (n - 1) * arrk[n - 1]

返回 F(0), F(1), ..., F(n-1)中的最大值 

生成的测试用例让答案符合 32 位 整数。

 

示例 1:

输入: nums = [4,3,2,6]
输出: 26
解释:
F(0) = (0 * 4) + (1 * 3) + (2 * 2) + (3 * 6) = 0 + 3 + 4 + 18 = 25
F(1) = (0 * 6) + (1 * 4) + (2 * 3) + (3 * 2) = 0 + 4 + 6 + 6 = 16
F(2) = (0 * 2) + (1 * 6) + (2 * 4) + (3 * 3) = 0 + 6 + 8 + 9 = 23
F(3) = (0 * 3) + (1 * 2) + (2 * 6) + (3 * 4) = 0 + 2 + 12 + 12 = 26
所以 F(0), F(1), F(2), F(3) 中的最大值是 F(3) = 26 。

示例 2:

输入: nums = [100]
输出: 0

 

提示:

  • n == nums.length
  • 1 <= n <= 105
  • -100 <= nums[i] <= 100
lightbulb

解题思路

方法一

1
2
3
4
5
6
7
8
9
10
class Solution:
    def maxRotateFunction(self, nums: List[int]) -> int:
        f = sum(i * v for i, v in enumerate(nums))
        n, s = len(nums), sum(nums)
        ans = f
        for i in range(1, n):
            f = f + s - n * nums[n - i]
            ans = max(ans, f)
        return ans
speed

复杂度分析

指标
时间Depends on the final approach
空间Depends on the final approach
psychology

面试官常问的追问

外企场景
  • question_mark

    Look for the candidate's understanding of state transition dynamic programming and its application to rotating arrays.

  • question_mark

    Evaluate how well the candidate avoids recalculating the sum for each rotation and instead uses previous results.

  • question_mark

    Assess if the candidate can optimize the algorithm to meet the problem's constraints, especially with a time complexity of O(n).

warning

常见陷阱

外企场景
  • error

    Failing to utilize dynamic programming, leading to redundant calculations for each rotation.

  • error

    Not maintaining the maximum function value during the iterations, which can result in incorrect answers.

  • error

    Overcomplicating the solution by recalculating the weighted sum from scratch for each rotation.

swap_horiz

进阶变体

外企场景
  • arrow_right_alt

    Rotate the array k positions to the left instead of the right.

  • arrow_right_alt

    Consider variations where the array elements are all the same, simplifying the rotation function calculation.

  • arrow_right_alt

    Change the weights used in the rotation function from simple indices to custom values based on a given formula.

help

常见问题

外企场景

旋转函数题解:状态·转移·动态规划 | LeetCode #396 中等