为有牺牲多壮志,敢教日月换新天。

[Swift]LeetCode1191. K 次串联后最大子数组之和 | K-Concatenation Maximum Sum

★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★
➤微信公众号:山青咏芝(shanqingyongzhi)
➤博客园地址:山青咏芝(www.zengqiang.org
➤GitHub地址:https://github.com/strengthen/LeetCode
➤原文地址:https://www.cnblogs.com/strengthen/p/11521662.html
➤如果链接不是山青咏芝的博客园地址,则可能是爬取作者的文章。
➤原文已修改更新!强烈建议点击原文地址阅读!支持作者!支持原创!
★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★

热烈欢迎,请直接点击!!!

进入博主App Store主页,下载使用各个作品!!!

注:博主将坚持每月上线一个新app!!!

Given an integer array arr and an integer k, modify the array by repeating it k times.

For example, if arr = [1, 2] and k = 3 then the modified array will be [1, 2, 1, 2, 1, 2].

Return the maximum sub-array sum in the modified array. Note that the length of the sub-array can be 0 and its sum in that case is 0.

As the answer can be very large, return the answer modulo 10^9 + 7.

 

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:

  • 1 <= arr.length <= 10^5
  • 1 <= k <= 10^5
  • -10^4 <= arr[i] <= 10^4

给你一个整数数组 arr 和一个整数 k

首先,我们要对该数组进行修改,即把原数组 arr 重复 k 次。

举个例子,如果 arr = [1, 2] 且 k = 3,那么修改后的数组就是 [1, 2, 1, 2, 1, 2]

然后,请你返回修改后的数组中的最大的子数组之和。

注意,子数组长度可以是 0,在这种情况下它的总和也是 0

由于 结果可能会很大,所以需要 模(mod) 10^9 + 7 后再返回。 

 

示例 1:

输入:arr = [1,2], k = 3
输出:9

示例 2:

输入:arr = [1,-2,1], k = 5
输出:2

示例 3:

输入:arr = [-1,-2], k = 7
输出:0

 

提示:

  • 1 <= arr.length <= 10^5
  • 1 <= k <= 10^5
  • -10^4 <= arr[i] <= 10^4

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 }

 

posted @ 2019-09-15 12:04  为敢技术  阅读(477)  评论(0编辑  收藏  举报