![]() |
VOOZH | about |
Given a circular array arr[], find the maximum sum of any non-empty subarray. A circular array allows wrapping from the end back to the beginning.
Note: A subarray may wrap around the end and continue from the beginning, forming a circular segment.
Examples:
Input: arr[] = [8, -8, 9, -9, 10, -11, 12]
Output: 22
Explanation: The circular subarray [12, 8, -8, 9, -9, 10] gives the maximum sum, which is 22.Input: arr[] = [4, -1, -2, 3]
Output: 7
Explanation: The circular subarray [3, 4] gives the maximum sum of 7.Input: arr[] = [5, -2, 3, 4]
Output: 12
Explanation: The circular subarray [3, 4, 5] gives the maximum sum of 12.
Table of Content
The idea is to consider every element as the beginning of the subarray, and calculate the maximum possible sum, which includes both circular and linear subarrays starting from that element.
22
In a circular array, the maximum subarray sum can be either the maximum normal sum, which is the highest sum of a non-circular array, or the maximum circular sum, which includes elements from both the start and the end of the array. The normal sum can be efficiently calculated using Kadane's algorithm. And, the circular sum is calculated by combining prefix sum and suffix sum.
22
This approach is similar to the previous one, but the key difference is that we're using Kadane's algorithm to find the circular subarray sum as well. The maximum sum of a circular subarray can be defined as the total sum of the array minus the sum of a subarray in the middle. So, to maximize the circular subarray sum, we need to minimize the subarray sum.
22