首页 > 代码库 > 396. Rotate Function

396. Rotate Function

  s0 = 0 * a0 + 1 *a1 + 2 * a2 + 3 * a3

-   s1 = 1 * a0 + 2 * a1 + 3 * a2 + 0 * a3

-------------------------------------------------

      - a0  - a1 - a2 + 3*a3 = - (a0+a1+a2+a3)+4*a4

所以如果sum表示所有数的和,len表示数组的长度那么每连续两个的差别是:

s0 - s1 = -sum + len*a3

所以公式就是

sn = sn-1 + sum - len * a[len - n]

 

 1     public int maxRotateFunction(int[] A) { 2         int initial = 0; 3         int sum = 0; 4         int len = A.length; 5         for(int i = 0; i < len; i++) { 6             sum += A[i]; 7             initial += i * A[i]; 8         } 9         int max = initial;10         for(int i = 1; i < len; i++) {11             initial = initial + sum - len * A[len - i];12             max = Math.max(max, initial);13         }14         return max;15     }

 

396. Rotate Function