标签:部分 img 子数组和 strong concat lock rcu 后缀 etc
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.
Input: arr = [1,2], k = 3
Output: 9
Input: arr = [1,-2,1], k = 5
Output: 2
Input: arr = [-1,-2], k = 7
Output: 0
- 1 <= arr.length <= 10^5
- 1 <= k <= 10^5
- -10^4 <= arr[i] <= 10^4
参考Maximum Sum Circular Subarray,可分为以下三种情况:
其中,第三种情况可以看作是第二种情况的结果假设(k-2)*sum(arr),即子数组和大于0时,第三种情况时肯定大于第二种情况的。最终结果取上面三种情况种的最大值即可。
class Solution:
def kConcatenationMaxSum(self, arr: List[int], k: int) -> int:
mod = pow(10, 9)+7
# 计算最大子数组和以及数组和
cur_max, total, max_sum = 0, 0, 0
for num in arr:
cur_max = max(cur_max+num, num)
max_sum = max(max_sum, cur_max)
total += num
if k == 1:
return max_sum%mod
# 计算最大前缀和
prefix_sum = 0
cur_sum = 0
for i in range(len(arr)):
cur_sum += arr[i]
prefix_sum = max(cur_sum, prefix_sum)
#计算最大后缀和
suffix_sum = 0
cur_sum = 0
for i in range(len(arr))[::-1]:
cur_sum += arr[i]
suffix_sum = max(cur_sum, suffix_sum)
if total > 0:
print(prefix_sum, suffix_sum, total)
return max(((k-2)*total+prefix_sum+suffix_sum)%mod, max_sum%mod)
else:
print(prefix_sum, suffix_sum, total)
return max((prefix_sum+suffix_sum)%mod, max_sum%mod)
Leetcode 1191. K-Concatenation Maximum Sum
标签:部分 img 子数组和 strong concat lock rcu 后缀 etc
原文地址:https://www.cnblogs.com/zhaoyinghe/p/12158096.html