在线时间:8:00-16:00
迪恩网络APP
随时随地掌握行业动态
扫描二维码
关注迪恩网络微信公众号
★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★ Given an integer array For example, if Return the maximum sub-array sum in the modified array. Note that the length of the sub-array can be As the answer can be very large, return the answer modulo
Example 1: Input: arr = [1,2], k = 3 Output: 9 Example 2: Input: arr = [1,-2,1], k = 5 Output: 2 Example 3: Input: arr = [-1,-2], k = 7 Output: 0
Constraints:
给你一个整数数组 首先,我们要对该数组进行修改,即把原数组
然后,请你返回修改后的数组中的最大的子数组之和。 注意,子数组长度可以是 由于 结果可能会很大,所以需要 模(mod)
示例 1: 输入:arr = [1,2], k = 3 输出:9 示例 2: 输入:arr = [1,-2,1], k = 5 输出:2 示例 3: 输入:arr = [-1,-2], k = 7 输出:0
提示:
Runtime: 396 ms
Memory Usage: 23.8 MB
1 class Solution { 2 func kConcatenationMaxSum(_ arr: [Int], _ k: Int) -> Int { 3 var arr = arr 4 var oneSum:Int = 0 5 for v in arr 6 { 7 oneSum += v 8 } 9 var ans:Int = 0 10 let len:Int = arr.count 11 if oneSum > 0 && k >= 2 12 { 13 var leftAns:Int = 0 14 var rightAns:Int = 0 15 var tmpAns:Int = 0 16 for i in 0..<len 17 { 18 tmpAns += arr[i] 19 leftAns = max(leftAns, tmpAns) 20 } 21 tmpAns = 0 22 for i in stride(from:len - 1,through:0,by:-1) 23 { 24 tmpAns += arr[i] 25 rightAns = max(rightAns, tmpAns) 26 } 27 ans = max(ans, leftAns + rightAns + (k-2) * oneSum) 28 } 29 if k > 1 30 { 31 arr += arr 32 } 33 var tmpAns:Int = 0 34 for v in arr 35 { 36 tmpAns += v 37 ans = max(ans, tmpAns) 38 if tmpAns < 0 39 { 40 tmpAns = 0 41 } 42 } 43 return ans%1000000007 44 } 45 }
|
请发表评论