問題:
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.
大意:
給出一個整型數(shù)組A雄人,設(shè)n為其長度。
假設(shè)Bk是將A進行k此順時針旋轉(zhuǎn)后的數(shù)組层皱,我們定義一個A的“旋轉(zhuǎn)函數(shù)”F识椰,如下:
F(k) = 0 * Bk[0] + 1 * Bk[1] + ... + (n-1) * Bk[n-1].
注意:
n保證不會超過10的5次方
例子: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.
思路:
這個題目的意思就是對A進行旋轉(zhuǎn)求多項式,每次旋轉(zhuǎn)系數(shù)移動一次鄙漏,旋轉(zhuǎn)一次求出一個結(jié)果嗤谚,看哪個最大就返回哪個棺蛛。
我的做法是直接進行每一個的計算然后找最大的,代碼挺簡單巩步,時間復(fù)雜度是O(n平方)旁赊,很長。
代碼(Java):
public class Solution {
public int maxRotateFunction(int[] A) {
if (A.length == 0) return 0;
int result = -2147483648;
for (int i = 0; i < A.length; i++) {
int sum = sum(A, A.length - i);
if (sum > result) result = sum;
}
return result;
}
public int sum(int[] A, int index) {
int sum = 0;
for (int i = 0; i < A.length; i++) {
if (index >= A.length) index = 0;
sum += i * A[index];
index ++;
}
return sum;
}
}
他山之石:
public class Solution {
public int maxRotateFunction(int[] A) {
int allSum = 0;
int len = A.length;
int F = 0;
for (int i = 0; i < len; i++) {
F += i * A[i];
allSum += A[i];
}
int max = F;
for (int i = len - 1; i >= 1; i--) {
F = F + allSum - len * A[i];
max = Math.max(F, max);
}
return max;
}
}
這個做法的好處在于只需要O(n)的時間椅野,快很多终畅。他對題目的要求進行了一些數(shù)學(xué)計算,然后得出了一個方便計算的式子竟闪,過程如下:
F(k) = 0 * Bk[0] + 1 * Bk[1] + ... + (n-1) * Bk[n-1]
F(k-1) = 0 * Bk-1[0] + 1 * Bk-1[1] + ... + (n-1) * Bk-1[n-1]
= 0 * Bk[1] + 1 * Bk[2] + ... + (n-2) * Bk[n-1] + (n-1) * Bk[0]
那么离福,
F(k) - F(k-1) = Bk[1] + Bk[2] + ... + Bk[n-1] + (1-n)Bk[0]
= (Bk[0] + ... + Bk[n-1]) - nBk[0]
= sum - nBk[0]
因此,
F(k) = F(k-1) + sum - nBk[0]
那Bk[0]是什么呢炼蛤?
k = 0; B[0] = A[0];
k = 1; B[0] = A[len-1];
k = 2; B[0] = A[len-2];
...
這樣妖爷,也就有了上面的代碼了。
合集:https://github.com/Cloudox/LeetCode-Record