Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- '''
- one point: inside of array means not a circular array.
- Logic:
- Any circular array will be having only two segment:
- i) maximum sum subarray
- ii)minimum sum subarray
- for eg. you are having maximum array in middle,if rest of the array will be having
- any positive part at any corner of maximum array then it will be for sure in the
- maximum array.
- Now,We will find maximum sum subarray and minimum sum subarray in normal array and
- sum of the array.
- case 1)all elements is negative : In this case,sum of array will be equal to minimum
- subarray and answer will be the minimum element ie. maximum sum subarray.
- case 2)Either maxiumum subarray or minimum subaray will come inside of normal array for sure.
- so if maximum subarray comes inside of array then answer is maximum subarray
- or if maximum subaray doesn't comes inside of array and it is one both end of array
- then minimum subarray will be definitely inside the array then we can find max subarray
- sum as totol sum - minimum subarray sum.
- '''
- class Solution:
- def maxSubarraySumCircular(self, nums):
- sum = 0
- cur_min = 0
- cur_max = 0
- _min = float('inf')
- _max = float('-inf')
- for i in range(len(nums)):
- sum += nums[i]
- cur_min += nums[i]
- _min = min(cur_min, _min)
- if cur_min > 0:
- cur_min = 0
- cur_max += nums[i]
- _max = max(cur_max, _max)
- if cur_max < 0:
- cur_max = 0
- if sum == _min:
- 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.
- else:
- 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.
Advertisement
Add Comment
Please, Sign In to add comment