当前位置:网站首页>Leetcode-396 rotation function

Leetcode-396 rotation function

2022-04-23 15:48:00 Mid year and early year boundary

Given a length of n Array of integers for nums .
hypothesis arrk It's an array nums Clockwise rotation k Array after position , We define nums Of Rotation function F by :
F(k) = 0 * arrk[0] + 1 * arrk[1] + … + (n - 1) * arrk[n - 1]
return F(0), F(1), …, F(n-1) Maximum of .
The generated test cases make the answers meet the requirements 32 position Integers .

 Example  1:

 Input : nums = [4,3,2,6]
 Output : 26
 explain :
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
 therefore  F(0), F(1), F(2), F(3)  The maximum value in is  F(3) = 26 .
 Example  2:

 Input : nums = [100]
 Output : 0

solution :

class Solution:
    def maxRotateFunction(self, nums: List[int]) -> int:
        n = len(nums)
        total = sum(nums)
        dp = [0]*n
        dp[0] = sum(num*idx for idx, num in enumerate(nums))
        for i in range(1,n):
            dp[i] = dp[i-1] + total - nums[-i]*n
        return max(dp)

版权声明
本文为[Mid year and early year boundary]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/04/202204231545223097.html