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.
每次做这种题都有一种小学时候在做奥赛的感觉,一开始用的暴力解法,毫无意外的TLE以后开始找规律。
观察题干首先我们可以发现在数组An次翻转以后得到的B数组,其实是A数组经过n次右移,并在每次右移后将最后一个元素挪到第一个后的结果。也就是:
k=0时,B[0]=A[0],
k=1时,B[0]=A[length-1],
k=2时,B[0]=A[length-2],
k=3时,B[0]=A[length-3]…………
k=n时,B[0]=A[length-n]
接下来探寻一下F[x]与F[x-1]之间的关系,不难发现因为系数的规律,在每次右移时,除了将要从最后一位移到第一位的A[length-n]之外,其余元素的系数都加了一,那么不妨先设sum=A[0]+A[1]+……+A[length-1],还可以发现F[x-1]比F[x]多了length-1个A[length-n],分析到这里我们已经可以列出F[x]与F[x-1]的关系式:
F[x]=F[x-1]-(length-1)*A[length-n]+sum-A[length-n]
化简后:
F[x]=F[x-1]+sum-length*A[length-n]
接下来转化为AC代码即可:
public class Solution {
public int maxRotateFunction(int[] A) {
int Sum = 0;
int len = A.length;
int F = 0;
for (int i = 0; i < len; i++) {
F += i * A[i];
Sum += A[i];
}
int max = F;
for (int i = len - 1; i >= 1; i--) {
F = F + Sum - len * A[i];
max = Math.max(F, max);
}
return max;
}
}