imashutosh51

K-Concatenation Maximum Sum

Oct 6th, 2022 (edited)
109
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 2.21 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. Even if the maximum sum of two array is including some last elements of the arr and some initial elements of the second array then also we will take the best suffix of first array then the k-1 array sum then the best prefix of the last array.
  14.  
  15. The maximum subarray sum can't be in between if the total sum of each array is positive arr = [-10, -10, 100, 100, -10], k=3 here total sum of a subarray is 170>0 and max subarray is [100,100] but two of them extended will be having max subarray as [100,100,-10,-10,-10,100,100]=370 so this will autoamtically come in case 3.
  16. '''
  17. from typing import List
  18.  
  19. class Solution:
  20.     def kConcatenationMaxSum(self, arr: List[int], k: int) -> int:
  21.         MOD = 10**9 + 7
  22.        
  23.         #handle k == 1 first because making arr to arr+arr will miss this case.
  24.         if k == 1:
  25.             cur = 0
  26.             ans = 0
  27.             for num in arr:
  28.                 cur += num
  29.                 ans = max(ans, cur)
  30.                 if cur < 0:
  31.                     cur = 0
  32.             return ans % MOD
  33.        
  34.         total = sum(arr)
  35.         arr2 = arr * 2
  36.        
  37.         # kadane on arr + arr
  38.         cur = 0
  39.         ans = 0
  40.         for num in arr2:
  41.             cur += num
  42.             ans = max(ans, cur)
  43.             if cur < 0:
  44.                 cur = 0
  45.        
  46.         if total > 0:
  47.             return (ans + (k - 2) * total) % MOD
  48.         else:
  49.             return ans % MOD
Advertisement
Add Comment
Please, Sign In to add comment