C++的实现:
1 class Solution { 2 public: 3 int maxRotateFunction(vector<int>& A) { 4 long N = A.size(); 5 long S = 0; 6 long t = 0; 7 for (int i = 0; i < N; ++i) { 8 S += A[i]; 9 t += i * A[i]; 10 } 11 long res = t; 12 for (int i = N - 1; i >= 0; --i) { 13 // F(k+1) = F(k) + S - n * Bk[n-1] 14 t += S - N * (long)A[i]; 15 res = max(res, t); 16 } 17 return res; 18 } 19 };
python的实现:
1 class Solution: 2 def maxRotateFunction(self, A: 'List[int]') -> int: 3 N,S,t = len(A),0,0 4 for i in range(N): 5 S += A[i]#原始数组之和 6 t += i * A[i]#旋转数组之和 7 res = t 8 for i in range(N-1,-1,-1): 9 t += S - N * A[i] 10 res = max(res,t) 11 return res
算法思路:数学题。
根据题目找规律,错位相减,以提高算法执行速度。
推导过程:
(1)F(k) = 0 * Bk[0] + 1 * Bk[1] + ... + (n-2) * Bk[n-2] + (n-1) * Bk[n-1]
(2)F(k+1) = 0 * Bk[n-1] + 1 * Bk[0] + 2 * Bk[2] + ... + (n-1) * Bk[n-2]
(2)-(1)得:F(k+1) - F(k) = (Bk[0] + Bk[1] + ... + Bk[n-2]) - (n-1)*Bk[n-1]
可得:F(k+1) - F(k) = (Bk[0] + Bk[1] + ... + Bk[n-2] + Bk[n-1]) - n*Bk[n-1]
令S=Sum{Bk}
有:F(k+1) = F(k) + S - n * Bk[n-1]
参考地址:https://leetcode-cn.com/problems/rotate-function/solution/c-cuo-wei-xiang-jian-fa-by-da-li-wang/