File tree Expand file tree Collapse file tree 1 file changed +32
-0
lines changed
Expand file tree Collapse file tree 1 file changed +32
-0
lines changed Original file line number Diff line number Diff line change 1+ def kadanes_algorithm (arr ):
2+ """Standard Kadane's Algorithm for maximum sum subarray."""
3+ max_ending_here = max_so_far = arr [0 ]
4+
5+ for num in arr [1 :]:
6+ max_ending_here = max (num , max_ending_here + num )
7+ max_so_far = max (max_so_far , max_ending_here )
8+
9+ return max_so_far
10+
11+ def max_circular_subarray (arr ):
12+ """Kadane's Algorithm variation for circular arrays."""
13+ max_kadane = kadanes_algorithm (arr )
14+
15+ # Compute total array sum
16+ total_sum = sum (arr )
17+
18+ # Invert the array elements
19+ inverted_arr = [- x for x in arr ]
20+
21+ # Find the maximum sum of the inverted array (minimum subarray sum)
22+ max_inverted_kadane = kadanes_algorithm (inverted_arr )
23+
24+ # The maximum circular sum is total_sum + max_inverted_kadane
25+ # If max_inverted_kadane is equal to total_sum, it means all elements are negative
26+ max_circular = total_sum + max_inverted_kadane if max_inverted_kadane != - total_sum else max_kadane
27+
28+ return max (max_kadane , max_circular )
29+
30+ # Example usage
31+ arr = [1 , - 2 , 4 , - 3 ]
32+ print ("Maximum sum subarray (circular):" , max_circular_subarray (arr ))
You can’t perform that action at this time.
0 commit comments