[Swift]LeetCode396. 旋转函数 | Rotate Function

原文地址:https://www.cnblogs.com/strengthen/p/10305657.html 

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 kpositions clock-wise, we define a "rotation function" F on A as follow:

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

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

Note:
n is guaranteed to be less than 105.

Example:

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

So the maximum value of F(0), F(1), F(2), F(3) is F(3) = 26.

给定一个长度为 n 的整数数组 A 。

假设 Bk 是数组 A 顺时针旋转 k 个位置后的数组,我们定义 A 的“旋转函数” F 为:

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

计算F(0), F(1), ..., F(n-1)中的最大值。

注意:
可以认为 n 的值小于 105。

示例:

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

所以 F(0), F(1), F(2), F(3) 中的最大值是 F(3) = 26 。

60ms
 1 class Solution {
 2     //F(i) = F(i-1) + sum - n*A[n-i]
 3     func maxRotateFunction(_ A: [Int]) -> Int {
 4         if A.isEmpty {return 0}
 5         var t:Int = 0
 6         var sum:Int = 0
 7         var n:Int = A.count
 8         for i in 0..<n
 9         {
10             sum += A[i]
11             t += i * A[i]
12         }
13         var res:Int = t
14         for i in 1..<n
15         {
16             t = t + sum - n * A[n - i]
17             res = max(res, t)
18         }
19         return res
20     }
21 }

64ms
 1 class Solution {
 2     func maxRotateFunction(_ A: [Int]) -> Int {
 3         // 假设 Bk 是数组 A 顺时针旋转 k 个位置后的数组
 4         // F(k) = F(k-1) + Sum(Bk) - Bk.count * Bk.last
 5         
 6         guard A.count > 1 else {
 7             return 0
 8         }
 9         
10         let sum = A.reduce(0, {$0 + $1})
11         var F0 = 0
12         for i in 0..<A.count {
13             F0 += i * A[i]
14         }
15         
16         var res = F0
17         var mx = res
18         let n = A.count
19         for i in 1..<A.count {
20             res = res + sum - n * A[n-i]
21             mx = max(mx, res)
22         }
23         
24         return mx
25     }
26 }
原文地址:https://www.cnblogs.com/strengthen/p/10305657.html