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
.
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
class Solution {
int mod = (int) Math.pow(10,9)+7;
public long kadane(int[] arr){
long best=Long.MIN_VALUE;
long current=0;
for(int i=0;i<arr.length;i++){
current=(current+arr[i])%mod;
if(current>best){
best=current;
}
if(current<0){
current=0;
}
}
return best;
}
public long bestPrefix(int[] arr){
long best=Long.MIN_VALUE;
long current=0;
for(int i=0;i<arr.length;i++){
current=(current+arr[i])%mod;
if(current>best)
best=current;
}
return best;
}
public long bestSuffix(int[] arr){
long best=Long.MIN_VALUE;
long current=0;
for(int i=arr.length-1;i>=0;i--){
current=(current+arr[i])%mod;
if(current>best)
best=current;
}
return best;
}
public int kConcatenationMaxSum(int[] arr, int k) {
long kadane=kadane(arr);
if(k==1){
return (int)kadane;
}
long bestPrefix=bestPrefix(arr);
long bestSuffix=bestSuffix(arr);
long sum=0;
for(int x:arr){
sum=(sum+x)%mod;
}
if(sum>0){
return (int)Math.max(Math.max(kadane,(bestSuffix+((k-2)*sum)%mod+bestPrefix)%mod),0);
}
else{
return (int)Math.max(Math.max(kadane,(bestSuffix+bestPrefix)%mod),0);
}
}
}