题目描述
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
思路
有三种情况。
- 数组中间,多个数组拼接的结果和一个数组的结果相同。
- 数组头部和尾部,两个数组连起来,尾部和头部拼起来。
- 数组总和≥0,尾部和首部连起来,中间加上 (k-2) 个数组。
代码
class Solution {
public:
int MOD = 1e9+7;
int kConcatenationMaxSum(vector<int>& arr, int k) {
long long res1 = maxSum(arr, 1);
long long res2 = maxSum(arr, 2);
if (k == 1) return res1;
if (k == 2) return max(res1, res2);
long long sum = accumulate(arr.begin(), arr.end(), 0LL) % MOD;
return max(res1, max(res2, res2+(k-2)*sum)) % MOD;
}
long long maxSum(vector<int>&arr, int n) {
long long sum = 0;
long long ans = 0;
while(n--) {
for (const auto& num : arr) {
sum = max(sum+num, 0LL) % MOD;
ans = max(ans, sum);
}
}
return ans;
}
};
不是很明白。。。还。。

本文介绍了一种解决最大子数组和问题的算法,特别是在数组重复k次后的场景中。通过分析数组的不同部分(中间、头部和尾部)来确定最大子数组的可能位置,并考虑了数组总和对结果的影响。

310

被折叠的 条评论
为什么被折叠?



