Maximum equlibrium sum in an array in C++

C++Server Side ProgrammingProgramming

Problem statement

Given an array arr[]. Find maximum value of prefix sum which is also suffix sum for index i in arr[].

Example

If input array is −

Arr[] = {1, 2, 3, 5, 3, 2, 1} then output is 11 as −

  • Prefix sum = arr[0..3] = 1 + 2 + 3 + 5 = 11 and
  • Suffix sum = arr[3..6] = 5 + 3 + 2 + 1 = 11

Algorithm

  • Traverse the array and store prefix sum for each index in array presum[], in which presum[i] stores sum of subarray arr[0..i]
  • Traverse array again and store suffix sum in another array suffsum[], in which suffsum[i] stores sum of subarray arr[i..n-1]
  • For each index check if presum[i] is equal to suffsum[i] and if they are equal then compare, there value with overall maximum so far

Example

 Live Demo

#include <bits/stdc++.h>
using namespace std;
int getMaxSum(int *arr, int n) {
   int preSum[n];
   int suffSum[n];
   int result = INT_MIN;
   preSum[0] = arr[0];
   for (int i = 1; i < n; ++i) {
      preSum[i] = preSum[i - 1] + arr[i];
   }
   suffSum[n - 1] = arr[n - 1];
   if (preSum[n - 1] == suffSum[n - 1]) {
      result = max(result, preSum[n - 1]);
   }
   for (int i = n - 2; i >= 0; --i) {
      suffSum[i] = suffSum[i + 1] + arr[i];
      if (suffSum[i] == preSum[i]) {
         result = max(result, preSum[i]);
      }
   }
   return result;
}
int main() {
   int arr[] = {1, 2, 3, 5, 3, 2, 1};
   int n = sizeof(arr) / sizeof(arr[0]);
   cout << "Max equlibrium sum = " << getMaxSum(arr, n) << endl;
   return 0;
}

Output

When you compile and execute above program. It generates following output −

Max equlibrium sum = 11
raja
Published on 10-Jan-2020 07:08:59
Advertisements