python leetcode 396. Rotate Function
阿新 • • 發佈:2018-11-30
兩個迴圈O(N^2)超時了
A = [4, 3, 2, 6] 長度n=4
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
探究F(0)和F(1) 關係
F(1)=(3* 6) + (0 * 4) + (1 * 3) + (2 * 2)-(3* 6)+(1* 4)+(1* 3)+(12)=F(0)+(1 * 6)+(1
=F(0)+sum(A)-nA[3]
同理可得 F(2)=F(1)+sum(A)-nA[2] F(3)=F(2)+sum(A)-n*A[1]
class Solution(object): def maxRotateFunction(self, A): """ :type A: List[int] :rtype: int """ if not A: return 0 n=len(A) res=0 mysum=0 for i in range(n): res+=i*A[i] mysum+=A[i] pre=res for j in range(n-1,0,-1): pre=pre+mysum-n*A[j] res=max(res,pre) return res