Monday, September 23, 2024
Google search engine
HomeLanguagesPhp Program for Maximum equilibrium sum in an array

Php 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 : 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!

Feeling lost in the world of random DSA topics, wasting time without progress? It’s time for a change! Join our DSA course, where we’ll guide you on an exciting journey to master DSA efficiently and on schedule.
Ready to dive in? Explore our Free Demo Content and join our DSA course, trusted by over 100,000 neveropen!

RELATED ARTICLES

Most Popular

Recent Comments