imashutosh51

Max Circular Subarray Sum

Oct 6th, 2022 (edited)
127
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 2.04 KB | None | 0 0
  1. '''
  2. one point: inside of array means not a circular array.
  3. Logic:
  4. Any circular array will be having only two segment:
  5. i) maximum sum subarray
  6. ii)minimum sum subarray
  7.  
  8. for eg. you are having maximum array in middle,if rest of the array will be having
  9. any positive part at any corner of maximum array then it will be for sure in the
  10. maximum array.
  11.  
  12. Now,We will find maximum sum subarray and minimum sum subarray in normal array and
  13. sum of the array.
  14.  
  15. case 1)all elements is negative : In this case,sum of array will be equal to minimum
  16.       subarray and answer will be the minimum element ie. maximum sum subarray.
  17.      
  18. case 2)Either maxiumum subarray or minimum subaray will come inside of normal array for sure.
  19.       so if maximum subarray comes inside of array then answer is maximum subarray
  20.       or if maximum subaray doesn't comes inside of array and it is one both end of array
  21.       then minimum subarray will be definitely inside the array then we can find max subarray
  22.       sum as totol sum - minimum subarray sum.
  23. '''
  24.  
  25. class Solution:
  26.     def maxSubarraySumCircular(self, nums):
  27.         sum = 0
  28.         cur_min = 0
  29.         cur_max = 0
  30.         _min = float('inf')
  31.         _max = float('-inf')
  32.  
  33.         for i in range(len(nums)):
  34.             sum += nums[i]
  35.  
  36.             cur_min += nums[i]
  37.             _min = min(cur_min, _min)
  38.             if cur_min > 0:
  39.                 cur_min = 0
  40.  
  41.             cur_max += nums[i]
  42.             _max = max(cur_max, _max)
  43.             if cur_max < 0:
  44.                 cur_max = 0
  45.  
  46.         if sum == _min:
  47.             return _max   #if all elements are negative,sum will equal to minimum subarray so answer will be maxium subarray sum ie. maximum element of the array.
  48.         else:
  49.             return max(_max, sum - _min)   #If both positive and  negative elements are there means either maxium array exist inside the array or at corner of array so there tow possibilties are there._max if inside the array otherwise negative array will be inside the array so sum-minimum_array_sum.
  50.  
Advertisement
Add Comment
Please, Sign In to add comment