這題我用了一個(gè)沒(méi)有用到數(shù)學(xué)的方法徐鹤,用list滾動(dòng)乘數(shù)的index去跟A相乘听绳。其實(shí)滾動(dòng)int [] A里的數(shù)字去跟index相乘也一樣颂碘,同樣要用一個(gè)list來(lái)滾動(dòng)。
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é)方法头岔,找了個(gè)簡(jiǎn)單的理解了下:
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;
}