[Swift]LeetCode396. 旋轉函數 | Rotate Function

原文地址:http://www.javashuo.com/article/p-uusjmicd-r.html 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:less

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).spa

Note:
n is guaranteed to be less than 105.code

Example:htm

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 。blog

假設 Bk 是數組 A 順時針旋轉 k 個位置後的數組,咱們定義 A 的「旋轉函數」 F 爲:get

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

計算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 }
相關文章
相關標籤/搜索