A B D均比较简单。先说C题
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
这里有个猜测,
如果K=1,那么我只需要算这个数组的最大子数组和即可。
如果K=2,那么我也只需要算这个数组的最大子数组和,只不过是多加了长度。
如果K>2,那么不需要再讨论什么子数组了,实际上和K<=2类似。所以K>2以后的数组,如果和大于0,则全都要。
class Solution { public: int kConcatenationMaxSum(vector<int>& arr, int k) { int sum1 = 0,sum2 = 0; int ant = 0; int sum3 = 0; int arrsize = arr.size(); for(int i = 0;i<arrsize;i++){ ant+=arr[i]; sum3+=arr[i]; sum1 = max(ant,sum1); if(ant<=0){ ant=0; } } ant = 0; for(int i = 0;i<arrsize*2;i++){ ant+=arr[i%arrsize]; sum2 = max(ant,sum2); if(ant<=0){ ant=0; } } if(k==1){ return sum1; } cout<<sum3<<" "<<sum1<<" "<<sum2<<endl; if(sum3>0){ for(int i=2;i<k;i++){ sum2 +=sum3; sum2%=1000000007; } } return sum2; } };
原文:https://www.cnblogs.com/yinghualuowu/p/11525205.html