前缀和的应用 II

应用

应用1:396. 旋转函数

题目

396. 旋转函数

给定一个长度为 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)中的最大值 。

示例 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 。

分析

假设数组 \(nums\) 的长度为 \(n\),根据旋转函数 \(F\) 的定义,可以得

\[\begin{aligned} F(0) &= 0 \times nums[0] + 1 \times nums[1] + \cdots + (n - 1) \times nums[n - 1] \\ F(1) &= 0 \times nums[n - 1] + 1 \times nums[0] + \cdots + (n - 1) \times nums[n - 2] \end{aligned} \]

上述两式相减,可得:

\[\begin{aligned} F(1) - F(0) &= nums[0] + nums[1] + \cdots + nums[n - 2] - (n - 1) \times nums[n - 1] \\ &= nums[0] + nums[1] + \cdots + nums[n - 2] + nums[n - 1] - n \times nums[n - 1] \\ &=\sum_{i=0}^{n-1}nums[i] - n \times nums[n - 1] \end{aligned} \]

同理,可得:

\[F(2) - F(1) = \sum_{i=0}^{n-1}nums[i] - n \times nums[n - 2] \]

通过观察,可以推广到一般情况:

\[F(x) - F(x-1) = \sum_{i=0}^{n-1}nums[i] - n \times nums[n - x] \]

其中,\(\sum_{i=0}^{n-1}nums[i]\) 是数组 \(nums\) 的所有元素之和 \(Sum\),可以很容易求出,因此,可以看出旋转函数 \(F(x)\) 当前值,可以通过前一项转移得到:

\[F(x) = F(x-1) + \sum_{i=0}^{n-1}nums[i] - n \times nums[n - x] \]

因此,我们只需要先求出首项 \(F(0)\),即可根据上述递推公式,得到所有的 \(F(1), F(2), ..., F(n - 1)\),然后,再找到最大的一个 \(F_{max}(x)\) 即可。

代码实现

class Solution:
    def maxRotateFunction(self, nums: List[int]) -> int:
        f, n, _sum = 0, len(nums), sum(nums)
        for i, num in enumerate(nums):
            f += i * num

        result = f
        for i in range(n - 1, 0, -1):
            f = f + _sum - n * nums[i]
            result = max(result, f)
        return result

参考:

posted @ 2023-06-08 18:21  LARRY1024  阅读(4)  评论(0编辑  收藏  举报