Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- /*
- Logic:
- case 1: if k==1,then maximum sum subarray will be answer.
- case 2: if sum<0 then answer will be extracted by two array only because if sum<0 for whole then why will
- you take whole array in sum.so answer will be maximum sum subarray of two array which will be
- partial sum of two array definitely.
- case 3: if sum>0 then find maxium sum of two array and sum of rest array*k-2 because 2 array you alread used
- so only k-2 array left.
- for eg. [-1,6,-4], k=3 then 6 is the maximum sum subarray.
- -1,6,-4,-1,6,-4,-1,6,-4 maxium sum subarray of two combined array is [6,-4,-1,6] ie.7
- so we are including elements of second array after the 6 if we have to combine with the third array but in answer , [6,-4,-1,6,-4,-1,6] we compensate it by leaving the same elements of last array.
- */
- int m=pow(10,9)+7;
- int kadanes(vector <int> arr){
- // for(auto itr:arr) cout<<itr<<" ";
- int cur_max=0,_max=INT_MIN,sum=0;
- for(int i=0;i<arr.size();i++){
- cur_max+=arr[i];
- _max=max(cur_max,_max);
- if(cur_max<0) cur_max=0;
- }
- return max(0,_max);
- }
- int mul(int n1,int n2){
- int ans=0;
- for(int i=0;i<n2;i++){
- ans+=n1;
- ans%=m;
- }
- return ans;
- }
- class Solution {
- public:
- int kConcatenationMaxSum(vector<int>& a, int k) {
- vector<int> arr=a;
- int sum=0;
- for(auto itr:a){ arr.push_back(itr); sum+=itr;}
- if(k==1) return kadanes(a);
- else if(sum<0) return kadanes(arr);
- else return (kadanes(arr)+mul(sum,k-2))%m;
- }
- };
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement