Arrays Linked Lists Questions Medium
To find the maximum sum subarray in a circular array, we can use the Kadane's algorithm with a slight modification.
First, we find the maximum sum subarray using Kadane's algorithm in the original array. This will give us the maximum sum subarray that does not wrap around the circular array.
Next, we find the minimum sum subarray using Kadane's algorithm in the original array. This will give us the minimum sum subarray that does not wrap around the circular array.
Now, to find the maximum sum subarray in the circular array, we subtract the minimum sum subarray from the total sum of the original array. This will give us the sum of the subarray that wraps around the circular array.
Finally, we compare the maximum sum subarray obtained from the first step with the sum of the subarray that wraps around the circular array obtained from the third step. The larger of the two will be the maximum sum subarray in the circular array.
Here is the step-by-step process:
1. Initialize variables maxSum and minSum to the first element of the array.
2. Initialize variables currentMax and currentMin to the first element of the array.
3. Initialize a variable totalSum to the first element of the array.
4. Iterate through the array starting from the second element:
- Update currentMax as the maximum of the current element and the sum of the current element and currentMax.
- Update currentMin as the minimum of the current element and the sum of the current element and currentMin.
- Update maxSum as the maximum of maxSum and currentMax.
- Update minSum as the minimum of minSum and currentMin.
- Update totalSum by adding the current element to it.
5. If maxSum is negative (indicating that all elements in the array are negative), return maxSum as the maximum sum subarray.
6. Otherwise, return the maximum of maxSum and (totalSum - minSum).
This approach has a time complexity of O(n) as we iterate through the array only once.