这题我用了一个没有用到数学的方法,用list滚动乘数的index去跟A相乘。其实滚动int [] A里的数字去跟index相乘也一样,同样要用一个list来滚动。
public int maxRotateFunction(int[] A) {
if (A == null || A.length == 0) return 0;
int n = A.length;
int max = Integer.MIN_VALUE;
List<Integer> list = new ArrayList<>();
for (int i = 0; i < n; i++) {
list.add(i);
}
for (int i = 0; i < n; i++) {
int product = 0;
for (int j = 0; j < n; j++) {
product += list.get(j) * A[j];
}
max = Math.max(max, product);
list.add(list.remove(0));
}
return max;
}
看了答案,高票的用了一些数学方法,找了个简单的理解了下:
public int maxRotateFunction(int[] A) {
if(A.length == 0){
return 0;
}
int sum =0, iteration = 0, len = A.length;
for(int i=0; i<len; i++){
sum += A[i];
iteration += (A[i] * i);
}
int max = iteration;
for(int j=1; j<len; j++){
// for next iteration lets remove one entry value of each entry and the prev 0 * k
iteration = iteration - sum + A[j-1]*len;
max = Math.max(max, iteration);
}
return max;
}