Open In App

Php Program for Maximum circular subarray sum

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)

MApproach: There can be two cases for the maximum sum:  

The following are implementations of the above method. 






<?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 = array(11, 10, -20, 5, -3, -5, 8, -13, 10); 
    $n = count($a);
    echo "Maximum circular sum is ". maxCircularSum($a, $n); 
  
// This code is contributed by rathbhupendra
?>

Output: 

Maximum circular sum is 31

Complexity Analysis:  

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!


Article Tags :