在线时间:8:00-16:00
迪恩网络APP
随时随地掌握行业动态
扫描二维码
关注迪恩网络微信公众号
★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★ Given an array of integers Assume
Calculate the maximum value of Note: 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 = [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 }
|
请发表评论