# LeetCode: 396. 旋转函数¶

## 1、题目描述¶

F(k) = 0 * Bk[0] + 1 * Bk[1] + ... + (n-1) * Bk[n-1]

A = [4, 3, 2, 6]

F(0) = (0 * 4) + (1 * 3) + (2 * 2) + (3 * 6) = 0 + 3 + 4 + 18 = 25
F(1) = (0 * 6) + (1 * 4) + (2 * 3) + (3 * 2) = 0 + 4 + 6 + 6 = 16
F(2) = (0 * 2) + (1 * 6) + (2 * 4) + (3 * 3) = 0 + 6 + 8 + 9 = 23
F(3) = (0 * 3) + (1 * 2) + (2 * 6) + (3 * 4) = 0 + 2 + 12 + 12 = 26



## 2、解题思路¶

​ 看到这道题，首先使用暴力破解肯定是行不通的，需要寻找规律

​ 根据一般规律，我们发现，前后两个之和之间的规律：

F(0) = (0 * 4) + (1 * 3) + (2 * 2) + (3 * 6)
F(1) = (0 * 6) + (1 * 4) + (2 * 3) + (3 * 2)
F(2) = (0 * 2) + (1 * 6) + (2 * 4) + (3 * 3)
F(1) - F(0) = 4 + 3 + 2 - (3 * 6)
F(2) - F(1) = 6 + 4 + 3 - (3 * 2)


​ 于是，我们找到规律了

F(k) - F(k-1) = sum(B) - n * B[n - k]
F(k) = F(k-1) + sum(B) - n * B[n - k]


​ 类似于动态规划，后面的求解依赖于前面的值，因此，我们就能根据这个直接求解，并且更新最大的和值

class Solution:
def maxRotateFunction(self, A):
"""
:type A: List[int]
:rtype: int
"""
length = len(A)
if length <= 1:
return 0

sums = sum(A)
dp = [0] * length
first = 0
for i in range(length):
first += i * A[i]

dp[0] = first
res = dp[0]
for i in range(1, length):
dp[i] = dp[i - 1] + sums - length * A[length - i]
res = max(res, dp[i])

return res