396. Rotate Function 移动加权求和,取最大值

[抄题]:

Given an array of integers A and let n to be its length.

Assume Bk to be an array obtained by rotating the array A k positions clock-wise, we define a "rotation function" F on A as follow:

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

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

Note:
n is guaranteed to be less than 105.

Example:

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

So the maximum value of F(0), F(1), F(2), F(3) is F(3) = 26.

 [暴力解法]:

时间分析:

空间分析:

 [优化后]:

时间分析:

空间分析:

[奇葩输出条件]:

[奇葩corner case]:

[思维问题]:

不知道从哪里入手:那就先初始化一个sum, iteration再说吧。然后推导出公式:

iteration = iteration - sum + A[j-1]*len;

[英文数据结构或算法,为什么不用别的数据结构或算法]:

[一句话思路]:

[输入量]:空: 正常情况:特大:特小:程序里处理到的特殊情况:异常情况(不合法不合理的输入):

[画图]:

[一刷]:

[二刷]:

[三刷]:

[四刷]:

[五刷]:

  [五分钟肉眼debug的结果]:

[总结]:

那就先初始化一个sum, iteration再说。先设置成0,再具体计算。

[复杂度]:Time complexity: O(n) Space complexity: O(1)

[算法思想:迭代/递归/分治/贪心]:

[关键模板化代码]:

[其他解法]:

[Follow Up]:

[LC给出的题目变变变]:

 [代码风格] :

 [是否头一次写此类driver funcion的代码] :

 [潜台词] :

class Solution {
    public int maxRotateFunction(int[] A) {
        //corner case
        int len = A.length;
        if (len == 0 || A == null) return 0;
        
        //initialization: sum, iteration
        int sum = 0; int iteration = 0;
        for (int i = 0; i < len; i++) {
            sum += A[i];
            iteration += A[i] * i;
        }
        
        //sum = iteration, from 1 to n, calculate the new max
        int max = iteration;
        for (int j = 1; j < len; j++) {
            iteration = iteration - sum + len * A[j - 1];
            max = Math.max(max, iteration);
        }
        
        return max;
    }
}
View Code
原文地址:https://www.cnblogs.com/immiao0319/p/9416853.html