Problem

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.

Note

oneSum是数组A各位累加和,patternSum是按照pattern对数组乘积变换后的累加和,max是题目所求的不同变换累加和的最大值。

oneSum = 1A + 1B + 1C + 1D;
patternSum = 0A + 1B + 2C + 3D;

然后做一个递归:每次对patternSum减少oneSum,并加上当前递归对应的A[i]*len,这样做的道理是什么呢:

max = patternSum = 0A + 1B + 2C + 3D;
A[i]*len = 4A;
patternSum = -A + 0B + 1C + 2D + 4A = 0B + 1C + 2D + 3A;
max = Math.max(max, patternSum)= Math.max(0A1B2C3D, 3A0B1C2D);

也就是说,每一次循环,相当于改变一次pattern,从0123到3012,再到2301,到1230结束,取这之中的最大值返回即可。

Solution

public class Solution {
    public int maxRotateFunction(int[] A) {
        if (A == null || A.length == 0) return 0;
        int oneSum = 0, len = A.length, patternSum = 0;
        for (int i = 0; i < len; i++) {
            oneSum += A[i];
            patternSum += (A[i] * i);
        }
        int max = patternSum;
        for (int i = 0; i < len; i++) {
            patternSum += len * A[i] - oneSum;
            max = Math.max(max, patternSum);
        }
        return max;
    }
}

linspiration
161 声望53 粉丝