1. 题目内容
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.
2. WA历程
第一天开始刷leetcode,看到这个题后第一个想法是遍历,于是有了第一版:
public int maxRotateFunction(int[] A) {
int max=0;
for(int i=A.length;i>0;i--){
int result=0;
for(int j=0;j<A.length;j++)
result+=A[(i+j)%A.length]*j;
if(result>max)
max=result;
}
return max;
}
结果wrong anwser了:
Input: [-2147483648,-2147483648]
Output: 0
Expected: -2147483648
然后将初始化改为Integer.MIN_VALUE又在下面的用例错了
Input: []
Output: -2147483648
Expected: 0
最终自己的答案是
public int maxRotateFunction(int[] A) {
if(A.length<1){
return 0;
}
int max=Integer.MIN_VALUE;
for(int i=A.length;i>0;i--){
int result=0;
for(int j=0;j<A.length;j++)
result+=A[(i+j)%A.length]*j;
if(result>max)
max=result;
}
return max;
}
超时
3. 教训
教训如下:
1.取大值的时候参考变量的初始化应为最小而不是0
2.输入数据的临界情况要着重考虑
3.N^2复杂度的算法还是不要交上去丢人了ORZ
4. 最后使用的答案
参考了一下网上的算法,一个通俗易懂的版本解释如下:
题目的通项递推公式为:
f(i)=f(i-1)+sum-N*A[N-i]
由此可得答案如下:
public int maxRotateFunction(int[] A) {
if(A.length<1)
return 0;
int sum = 0,result=Integer.MIN_VALUE,f=0,length=A.length;
//calc sum, calc f(0)
for(int i=0;i<length;i++){
sum+=A[i];
f+=i*A[i];
}
for(int i=0;i<length;i++){
if(f>result)
result=f;
f=f+sum-length*A[length-1-i];
}
return result;
}