加载中...
396-旋转函数(Rotate Function)
发表于:2021-12-03 | 分类: 中等
字数统计: 620 | 阅读时长: 3分钟 | 阅读量:

原文链接: https://leetcode-cn.com/problems/rotate-function

英文原文

You are given an integer array nums of length n.

Assume arrk to be an array obtained by rotating nums by k positions clock-wise. We define the rotation function F on nums as follow:

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

Return the maximum value of F(0), F(1), ..., F(n-1).

The test cases are generated so that the answer fits in a 32-bit integer.

 

Example 1:

Input: nums = [4,3,2,6]
Output: 26
Explanation:
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
So the maximum value of F(0), F(1), F(2), F(3) is F(3) = 26.

Example 2:

Input: nums = [100]
Output: 0

 

Constraints:

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

中文题目

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

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

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

计算F(0), F(1), ..., F(n-1)中的最大值。

注意:
可以认为 n 的值小于 105

示例:

A = [4, 3, 2, 6]

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 。

通过代码

高赞题解

解题思路

推导过程:
(1)F(k) = 0 * Bk[0] + 1 * Bk[1] + ... + (n-2) * Bk[n-2] + (n-1) * Bk[n-1]
(2)F(k+1) = 0 * Bk[n-1] + 1 * Bk[0] + 2 * Bk[2] + ... + (n-1) * Bk[n-2]
(2)-(1)得:F(k+1) - F(k) = (Bk[0] + Bk[1] + ... + Bk[n-2]) - (n-1)*Bk[n-1]
可得:F(k+1) - F(k) = (Bk[0] + Bk[1] + ... + Bk[n-2] + Bk[n-1]) - n*Bk[n-1]
S=Sum{Bk}
有:F(k+1) = F(k) + S - n * Bk[n-1]

代码

class Solution {
public:
    int maxRotateFunction(vector<int>& A) {
        long N = A.size();
        long S = 0;
        long t = 0;
        for (int i = 0; i < N; ++i) {
            S += A[i];
            t += i * A[i];
        }
        long res = t;
        for (int i = N - 1; i >= 0; --i) {
            // F(k+1) = F(k) + S - n * Bk[n-1]
            t += S - N * (long)A[i];
            res = max(res, t);
        }
        return res;
    }
};

image.png

统计信息

通过次数 提交次数 AC比率
9936 22819 43.5%

提交历史

提交时间 提交结果 执行时间 内存消耗 语言
上一篇:
395-至少有 K 个重复字符的最长子串(Longest Substring with At Least K Repeating Characters)
下一篇:
397-整数替换(Integer Replacement)
本文目录
本文目录