美文网首页
LeetCode 396: Rotate Function (P

LeetCode 396: Rotate Function (P

作者: KRummy | 来源:发表于2018-06-21 15:45 被阅读0次

    题目

    Given an array of integers A and let n to be its length.

    Assume Bk to be an array obtained by rotating the array A k positions clock-wise, we define a "rotation function" F on A as follow:

    Calculate the maximum value of F(0), F(1), ..., F(n-1).

    思路

    错位相减即可。

    得到公式

    使用这个递推公式就可在O(n)时间内完成计算。

    代码

    class Solution(object):
        def maxRotateFunction(self, A):
            """
            :type A: List[int]
            :rtype: int
            """
            n = len(A)
            sm = sum(A)
            F = sum([i * A[i] for i in range(n)]) # F0
            maxF = F
            for k in range(1, n):
                F = F + sm - n * A[n - k]
                maxF = max(maxF, F)
            return maxF
    

    相关文章

      网友评论

          本文标题:LeetCode 396: Rotate Function (P

          本文链接:https://www.haomeiwen.com/subject/flaqyftx.html