Advertisement
imashutosh51

K-Concatenation Maximum Sum

Oct 6th, 2022 (edited)
47
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.56 KB | None | 0 0
  1. /*
  2. Logic:
  3. case 1: if k==1,then maximum sum subarray will be answer.
  4. case 2: if sum<0 then answer will be extracted by two array only because if sum<0 for whole then why will
  5.         you take whole array in sum.so answer will be maximum sum subarray of two array  which will be
  6.         partial sum of two array definitely.
  7. 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
  8.         so only k-2 array left.
  9. for eg. [-1,6,-4], k=3  then 6 is the maximum sum subarray.
  10. -1,6,-4,-1,6,-4,-1,6,-4 maxium sum subarray of two combined array is [6,-4,-1,6] ie.7
  11. 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.
  12. */
  13.  
  14. int m=pow(10,9)+7;
  15. int kadanes(vector <int> arr){
  16.     // for(auto itr:arr) cout<<itr<<" ";
  17.     int cur_max=0,_max=INT_MIN,sum=0;
  18.     for(int i=0;i<arr.size();i++){
  19.             cur_max+=arr[i];
  20.             _max=max(cur_max,_max);
  21.             if(cur_max<0) cur_max=0;
  22.         }
  23.     return max(0,_max);
  24. }
  25. int mul(int n1,int n2){
  26.     int ans=0;
  27.     for(int i=0;i<n2;i++){
  28.         ans+=n1;
  29.         ans%=m;
  30.     }
  31.     return ans;
  32. }
  33. class Solution {
  34. public:
  35.     int kConcatenationMaxSum(vector<int>& a, int k) {
  36.         vector<int> arr=a;
  37.         int sum=0;
  38.         for(auto itr:a){ arr.push_back(itr); sum+=itr;}
  39.         if(k==1) return kadanes(a);
  40.         else if(sum<0) return kadanes(arr);
  41.         else return (kadanes(arr)+mul(sum,k-2))%m;
  42.     }
  43. };
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement