這題我用了一個沒有用到數(shù)學(xué)的方法,用list滾動乘數(shù)的index去跟A相乘。其實滾動int [] A里的數(shù)字去跟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;
}
看了答案,高票的用了一些數(shù)學(xué)方法,找了個簡單的理解了下:
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;
}