Open In App

Php Program for Maximum equilibrium sum in an array

Improve
Improve
Like Article
Like
Save
Share
Report

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 : 4
Prefix sum of arr[0..3] = 
            Suffix sum of arr[3..6]

Input : arr[] = {-2, 5, 3, 1, 2, 6, -4, 2}
Output : 7
Prefix sum of arr[0..3] = 
              Suffix sum of arr[3..7]

A Simple Solution is to one by one check the given condition (prefix sum equal to suffix sum) for every element and returns the element that satisfies the given condition with maximum value. 

PHP




<?php
// PHP program to find
// maximum equilibrium sum.
 
// Function to find
// maximum equilibrium sum.
function findMaxSum( $arr, $n)
{
    $res = PHP_INT_MIN;
    for ( $i = 0; $i < $n; $i++)
    {
    $prefix_sum = $arr[$i];
    for ( $j = 0; $j < $i; $j++)
        $prefix_sum += $arr[$j];
 
    $suffix_sum = $arr[$i];
    for ( $j = $n - 1; $j > $i; $j--)
        $suffix_sum += $arr[$j];
 
    if ($prefix_sum == $suffix_sum)
        $res = max($res, $prefix_sum);
    }
    return $res;
}
 
// Driver Code
$arr = array(-2, 5, 3, 1,
              2, 6, -4, 2 );
$n = count($arr);
echo findMaxSum($arr, $n);
 
// This code is contributed by anuj_67.
?>


Output : 

7

 

Time Complexity: O(n2
Auxiliary Space: O(n)

A Better Approach is to traverse the array and store prefix sum for each index in array presum[], in which presum[i] stores sum of subarray arr[0..i]. Do another traversal of the array and store suffix sum in another array suffsum[], in which suffsum[i] stores sum of subarray arr[i..n-1]. After this for each index check if presum[i] is equal to suffsum[i] and if they are equal then compare their value with the overall maximum so far.

Output: 

7

 

Time Complexity: O(n) 
Auxiliary Space: O(n)

Please refer complete article on Maximum equilibrium sum in an array for more details!



Last Updated : 26 Dec, 2022
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads