给定一个长度为 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 。
class Solution { public int maxRotateFunction(int[] nums) { int Fk = 0; int max = 0; int temp = 0; //计算 F(0),F(1),...,F(N-1),比较求最大值 for(int i = 0; i < nums.length; i++) { for(int j = 0; j < nums.length; j++) { //Bk[i] = A[ (i+A.length-k) % A.length ] temp = (j + nums.length - i) % nums.length; Fk += j * nums[temp]; } if(0 == i) max = Fk; if(Fk > max) max = Fk; Fk = 0; } return max; } }
/** *错位相减法 * F(k) = 0*Bk[0] + 1*Bk[1] +...+ (n-2)*Bk[n-2] + (n-1)*Bk[n-1] * F(k+1) = 0*Bk[n-1] + 1*Bk[0] +...+ (n-1)*Bk[n-2] * F(k+1) = 1*Bk[0] + 2*Bk[1] +...+ (n-1)*Bk[n-2] + 0*Bk[n-1] * F(k+1) - F(k) = Bk[0] + +...+ Bk[n-2] - (n-1)*Bk[n-1] * F(k+1) - F(k) = Bk[0] +...+ Bk[n-1] -n*Bk[n-1] * F(k+1) = F(k) + sum(A) -n*Bk[n-1] */ class Solution { public int maxRotateFunction(int[] nums) { int Fk = 0; int max = 0; int sum = 0; //计算 F(0)和 sum(A) for(int i = 0; i < nums.length; i++) { Fk += i * nums[i]; sum += nums[i]; } max = Fk; for(int i = 0; i < nums.length; i++) { //F(k+1) = F(k) + sum(A) -n*Bk[n-1] Fk = Fk + sum - nums.length * nums[nums.length-i-1]; //比较 Fk求最大值 if(Fk > max) max = Fk; } return max; } }