Python3 Program for Maximum circular subarray sum
Last Updated :
06 Sep, 2024
Given n numbers (both +ve and -ve), arranged in a circle, find the maximum sum of consecutive numbers.
Examples:
Input: a[] = {8, -8, 9, -9, 10, -11, 12}
Output: 22 (12 + 8 - 8 + 9 - 9 + 10)
Input: a[] = {10, -3, -4, 7, 6, 5, -4, -1}
Output: 23 (7 + 6 + 5 - 4 -1 + 10)
Input: a[] = {-1, 40, -14, 7, 6, 5, -4, -1}
Output: 52 (7 + 6 + 5 - 4 - 1 - 1 + 40)
Method 1 There can be two cases for the maximum sum:
- Case 1: The elements that contribute to the maximum sum are arranged such that no wrapping is there. Examples: {-10, 2, -1, 5}, {-2, 4, -1, 4, -1}. In this case, Kadane's algorithm will produce the result.
- Case 2: The elements which contribute to the maximum sum are arranged such that wrapping is there. Examples: {10, -12, 11}, {12, -5, 4, -8, 11}. In this case, we change wrapping to non-wrapping. Let us see how. Wrapping of contributing elements implies non-wrapping of non-contributing elements, so find out the sum of non-contributing elements and subtract this sum from the total sum. To find out the sum of non-contributions, invert the sign of each element and then run Kadane's algorithm.
Our array is like a ring and we have to eliminate the maximum continuous negative that implies maximum continuous positive in the inverted arrays. Finally, we compare the sum obtained in both cases and return the maximum of the two sums.
The following are implementations of the above method.
Python
# Python program for maximum contiguous circular sum problem
# Standard Kadane's algorithm to find maximum subarray sum
def kadane(a):
n = len(a)
max_so_far = 0
max_ending_here = 0
for i in range(0, n):
max_ending_here = max_ending_here + a[i]
if (max_ending_here < 0):
max_ending_here = 0
if (max_so_far < max_ending_here):
max_so_far = max_ending_here
return max_so_far
# The function returns maximum circular contiguous sum in
# a[]
def maxCircularSum(a):
n = len(a)
# Case 1: get the maximum sum using standard kadane's
# algorithm
max_kadane = kadane(a)
# Case 2: Now find the maximum sum that includes corner
# elements.
max_wrap = 0
for i in range(0, n):
max_wrap += a[i]
a[i] = -a[i]
# Max sum with corner elements will be:
# array-sum - (-max subarray sum of inverted array)
max_wrap = max_wrap + kadane(a)
# The maximum circular sum will be maximum of two sums
if max_wrap > max_kadane:
return max_wrap
else:
return max_kadane
# Driver function to test above function
a = [11, 10, -20, 5, -3, -5, 8, -13, 10]
print "Maximum circular sum is", maxCircularSum(a)
# This code is contributed by Devesh Agrawal
Output:
Maximum circular sum is 31
Complexity Analysis:
- Time Complexity: O(n), where n is the number of elements in the input array.
As only linear traversal of the array is needed. - Auxiliary Space: O(1).
As no extra space is required.
Note that the above algorithm doesn't work if all numbers are negative, e.g., {-1, -2, -3}. It returns 0 in this case. This case can be handled by adding a pre-check to see if all the numbers are negative before running the above algorithm.
Method 2
Approach: In this method, modify Kadane's algorithm to find a minimum contiguous subarray sum and the maximum contiguous subarray sum, then check for the maximum value between the max_value and the value left after subtracting min_value from the total sum.
Algorithm
- We will calculate the total sum of the given array.
- We will declare the variable curr_max, max_so_far, curr_min, min_so_far as the first value of the array.
- Now we will use Kadane's Algorithm to find the maximum subarray sum and minimum subarray sum.
- Check for all the values in the array:-
- If min_so_far is equaled to sum, i.e. all values are negative, then we return max_so_far.
- Else, we will calculate the maximum value of max_so_far and (sum - min_so_far) and return it.
The implementation of the above method is given below.
Python
# Python program for maximum contiguous circular sum problem
# The function returns maximum
# circular contiguous sum in a[]
def maxCircularSum(a, n):
# Corner Case
if (n == 1):
return a[0]
# Initialize sum variable which
# store total sum of the array.
sum = 0
for i in range(n):
sum += a[i]
# Initialize every variable
# with first value of array.
curr_max = a[0]
max_so_far = a[0]
curr_min = a[0]
min_so_far = a[0]
# Concept of Kadane's Algorithm
for i in range(1, n):
# Kadane's Algorithm to find Maximum subarray sum.
curr_max = max(curr_max + a[i], a[i])
max_so_far = max(max_so_far, curr_max)
# Kadane's Algorithm to find Minimum subarray sum.
curr_min = min(curr_min + a[i], a[i])
min_so_far = min(min_so_far, curr_min)
if (min_so_far == sum):
return max_so_far
# returning the maximum value
return max(max_so_far, sum - min_so_far)
# Driver code
a = [11, 10, -20, 5, -3, -5, 8, -13, 10]
n = len(a)
print("Maximum circular sum is", maxCircularSum(a, n))
# This code is contributes by subhammahato348
Output:
Maximum circular sum is 31
Complexity Analysis:
- Time Complexity: O(n), where n is the number of elements in the input array.
As only linear traversal of the array is needed. - Auxiliary Space: O(1).
As no extra space is required.
Please refer complete article on
Maximum circular subarray sum for more details!
Similar Reads
Python Program for Maximum Product Subarray Given an array that contains both positive and negative integers, find the product of the maximum product subarray. Expected Time complexity is O(n) and only O(1) extra space can be used.Examples:Input: arr[] = {6, -3, -10, 0, 2}Output: 180 // The subarray is {6, -3, -10}Input: arr[] = {-1, -3, -10,
4 min read
Python3 Program for Size of The Subarray With Maximum Sum An array is given, find length of the subarray having maximum sum.Examples : Input : a[] = {1, -2, 1, 1, -2, 1}Output : Length of the subarray is 2Explanation: Subarray with consecutive elements and maximum sum will be {1, 1}. So length is 2Input : ar[] = { -2, -3, 4, -1, -2, 1, 5, -3 }Output : Leng
4 min read
Python3 Program for Maximum equilibrium sum in an array Given an array arr[]. Find the maximum value of prefix sum which is also suffix sum for index i in arr[].Examples : Input : arr[] = {-1, 2, 3, 0, 3, 2, -1}Output : 4Prefix sum of arr[0..3] = Suffix sum of arr[3..6]Input : arr[] = {-2, 5, 3, 1, 2, 6, -4, 2}Output : 7Prefix sum of arr[0..3] = Suffix s
3 min read
Python3 Program to Find the K-th Largest Sum Contiguous Subarray Given an array of integers. Write a program to find the K-th largest sum of contiguous subarray within the array of numbers which has negative and positive numbers.Examples: Input: a[] = {20, -5, -1} k = 3Output: 14Explanation: All sum of contiguous subarrays are (20, 15, 14, -5, -6, -1) so the 3rd
3 min read
Python - Sort Matrix by K Sized Subarray Maximum Sum Given Matrix, write a Python program to sort rows by maximum of K sized subarray sum. Examples: Input : test_list = [[4, 3, 5, 2, 3], [6, 4, 2, 1, 1], [4, 3, 9, 3, 9], [5, 4, 3, 2, 1]], K = 3 Output : [[4, 3, 5, 2, 3], [6, 4, 2, 1, 1], [5, 4, 3, 2, 1], [4, 3, 9, 3, 9]] Explanation : 12 = 12 = 12
4 min read
Python Program For Finding Subarray With Given Sum - Set 1 (Nonnegative Numbers) Given an unsorted array of nonnegative integers, find a continuous subarray which adds to a given number. Examples : Input: arr[] = {1, 4, 20, 3, 10, 5}, sum = 33 Output: Sum found between indexes 2 and 4 Sum of elements between indices 2 and 4 is 20 + 3 + 10 = 33 Input: arr[] = {1, 4, 0, 0, 3, 10,
5 min read
Python Program for Number of pairs with maximum sum Write a python program for a given array arr[], count number of pairs arr[i], arr[j] such that arr[i] + arr[j] is maximum and i < j. Example: Input : arr[] = {1, 1, 1, 2, 2, 2}Output: 3Explanation: The maximum possible pair sum where i<j is 4, which is given by 3 pairs, so the answer is 3 the
3 min read
Python | Maximum Sum Sublist The task is to find a contiguous sublist (i.e., a sequence of elements that appear consecutively in the original list) such that the sum of the elements in this sublist is as large as possible. We need to return the maximum sum of this sublist. Let's explore methods to find Maximum Sum Sublist in py
2 min read
Python3 Program for Queries to find maximum sum contiguous subarrays of given length in a rotating array Given an array arr[] of N integers and Q queries of the form {X, Y} of the following two types:If X = 1, rotate the given array to the left by Y positions.If X = 2, print the maximum sum subarray of length Y in the current state of the array.Examples: Input: N = 5, arr[] = {1, 2, 3, 4, 5}, Q = 2, Qu
4 min read
Python Program to Find the Maximum sum of i*arr[i] among all rotations of a given array Given an array arr[] of n integers, find the maximum that maximizes the sum of the value of i*arr[i] where i varies from 0 to n-1.Examples: Input: arr[] = {8, 3, 1, 2}Output: 29Explanation: Lets look at all the rotations,{8, 3, 1, 2} = 8*0 + 3*1 + 1*2 + 2*3 = 11{3, 1, 2, 8} = 3*0 + 1*1 + 2*2 + 8*3 =
5 min read