更一般地,当 $1 \le k \lt n$ 时,$F(k) = F(k-1) + \textit{numSum} - n \times \textit{nums}[n-k]$。我们可以不停迭代计算出不同的 $F(k)$,并求出最大值。
代码
[sol1-Python3]
1 2 3 4 5 6 7 8 9 10
classSolution: defmaxRotateFunction(self, nums: List[int]) -> int: f, n, numSum = 0, len(nums), sum(nums) for i, num inenumerate(nums): f += i * num res = f for i inrange(n - 1, 0, -1): f = f + numSum - n * nums[i] res = max(res, f) return res
[sol1-Java]
1 2 3 4 5 6 7 8 9 10 11 12 13 14
classSolution { publicintmaxRotateFunction(int[] nums) { intf=0, n = nums.length, numSum = Arrays.stream(nums).sum(); for (inti=0; i < n; i++) { f += i * nums[i]; } intres= f; for (inti= n - 1; i > 0; i--) { f += numSum - n * nums[i]; res = Math.max(res, f); } return res; } }
[sol1-C#]
1 2 3 4 5 6 7 8 9 10 11 12 13 14
publicclassSolution { publicintMaxRotateFunction(int[] nums) { int f = 0, n = nums.Length, numSum = nums.Sum(); for (int i = 0; i < n; i++) { f += i * nums[i]; } int res = f; for (int i = n - 1; i > 0; i--) { f += numSum - n * nums[i]; res = Math.Max(res, f); } return res; } }
[sol1-C++]
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
classSolution { public: intmaxRotateFunction(vector<int>& nums){ int f = 0, n = nums.size(); int numSum = accumulate(nums.begin(), nums.end(), 0); for (int i = 0; i < n; i++) { f += i * nums[i]; } int res = f; for (int i = n - 1; i > 0; i--) { f += numSum - n * nums[i]; res = max(res, f); } return res; } };
[sol1-C]
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
#define MAX(a, b) ((a) > (b) ? (a) : (b))
intmaxRotateFunction(int* nums, int numsSize){ int f = 0, numSum = 0; for (int i = 0; i < numsSize; i++) { f += i * nums[i]; numSum += nums[i]; } int res = f; for (int i = numsSize - 1; i > 0; i--) { f += numSum - numsSize * nums[i]; res = MAX(res, f); } return res; }
[sol1-JavaScript]
1 2 3 4 5 6 7 8 9 10 11 12
var maxRotateFunction = function(nums) { let f = 0, n = nums.length, numSum = _.sum(nums); for (let i = 0; i < n; i++) { f += i * nums[i]; } let res = f; for (let i = n - 1; i > 0; i--) { f += numSum - n * nums[i]; res = Math.max(res, f); } return res; };
funcmaxRotateFunction(nums []int)int { numSum := 0 for _, v := range nums { numSum += v } f := 0 for i, num := range nums { f += i * num } ans := f for i := len(nums) - 1; i > 0; i-- { f += numSum - len(nums)*nums[i] ans = max(ans, f) } return ans }
funcmax(a, b int)int { if b > a { return b } return a }