PHP Program for Maximum Circular Subarray Sum
Last Updated :
22 Jul, 2024
Given n numbers (both +ve and -ve), arranged in a circle, find the maximum sum of consecutive numbers.
Examples:
Input: Arr = [ 8, -8, 9, -9, 10, -11, 12 ]
Output: 22 (12 + 8 - 8 + 9 - 9 + 10)
Input: Arr = [ 10, -3, -4, 7, 6, 5, -4, -1 ]
Output: 23 (7 + 6 + 5 - 4 -1 + 10)
Input: Arr = [ -1, 40, -14, 7, 6, 5, -4, -1 ]
Output: 52 (7 + 6 + 5 - 4 - 1 - 1 + 40)
Approach: 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 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.
PHP
<?php
// PHP program for maximum
// contiguous circular sum problem
// The function returns maximum
// circular contiguous sum $a[]
function maxCircularSum($a, $n) {
// Case 1: get the maximum sum
// using standard kadane' s algorithm
$max_kadane = kadane($a, $n);
// Case 2: Now find the maximum
// sum that includes corner elements.
$max_wrap = 0;
for ($i = 0; $i < $n; $i++) {
$max_wrap += $a[$i]; // Calculate array-sum
$a[$i] = -$a[$i]; // invert the array (change sign)
}
// max sum with corner elements will be:
// array-sum - (-max subarray sum of inverted array)
$max_wrap = $max_wrap + kadane($a, $n);
// The maximum circular sum will be maximum of two sums
return $max_wrap > $max_kadane ? $max_wrap : $max_kadane;
}
// Standard Kadane's algorithm to
// find maximum subarray sum
function kadane($a, $n) {
$max_so_far = 0;
$max_ending_here = 0;
for ($i = 0; $i < $n; $i++) {
$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;
}
/* Driver code */
$a = [11, 10, -20, 5, -3, -5, 8, -13, 10];
$n = count($a);
echo "Maximum circular sum is " . maxCircularSum($a, $n);
?>
OutputMaximum 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.
Please refer complete article on Maximum circular subarray sum for more details!
Similar Reads
Maximum Subarray Sum - Kadane's Algorithm Given an array arr[], the task is to find the subarray that has the maximum sum and return its sum.Examples:Input: arr[] = {2, 3, -8, 7, -1, 2, 3}Output: 11Explanation: The subarray {7, -1, 2, 3} has the largest sum 11.Input: arr[] = {-2, -4}Output: -2Explanation: The subarray {-2} has the largest s
9 min read
PHP Tutorial PHP is a widely used, open-source server-side scripting language primarily designed for web development. It is embedded directly into HTML and generates dynamic content on web pages, making it essential for building data-driven websites. It allows developers to handle database interactions, session
9 min read
Circular Array Implementation of Queue A Circular Queue is a way of implementing a normal queue where the last element of the queue is connected to the first element of the queue forming a circle.The operations are performed based on the FIFO (First In First Out) principle. It is also called 'Ring Buffer'. In a normal Queue, we can inser
8 min read
Top 60+ PHP Interview Questions and Answers -2025 PHP is a popular server-side scripting language, widely known for its efficiency in web development and versatility across various platforms. PHP is extensively utilized by top companies such as Facebook, WordPress, Slack, Wikipedia, MailChimp, and many more due to its robust features and high perfo
15+ min read
PHP Introduction PHP stands for Hypertext Preprocessor. It is an open-source, widely used language for web development. Developers can create dynamic and interactive websites by embedding PHP code into HTML. PHP can handle data processing, session management, form handling, and database integration. The latest versi
8 min read
PHP Arrays Arrays are one of the most important data structures in PHP. They allow you to store multiple values in a single variable. PHP arrays can hold values of different types, such as strings, numbers, or even other arrays. Understanding how to use arrays in PHP is important for working with data efficien
5 min read
Version Control Systems Version Control Systems (VCS) are essential tools used in software development and collaborative projects to track and manage changes to code, documents, and other files. Whether you're working alone or as part of a team, version control helps ensure that your work is safe, organized, and easy to co
7 min read
PHP | Functions A function in PHP is a self-contained block of code that performs a specific task. It can accept inputs (parameters), execute a set of statements, and optionally return a value. PHP functions allow code reusability by encapsulating a block of code to perform specific tasks.Functions can accept param
8 min read
Difference between HTTP GET and POST Methods HTTP (Hypertext Transfer Protocol) specifies a collection of request methods to specify what action is to be performed on a particular resource. The most commonly used HTTP request methods are GET, POST, PUT, PATCH, and DELETE. This article covers the 2 most common HTTP request methods, i.e. the GET
4 min read
Subarrays, Subsequences, and Subsets in Array What is a Subarray?A subarray is a contiguous part of array, i.e., Subarray is an array that is inside another array. In general, for an array of size n, there are n*(n+1)/2 non-empty subarrays. For example, Consider the array [1, 2, 3, 4], There are 10 non-empty sub-arrays. The subarrays are: (1),
10 min read