ancing Array

QUESTION

Find the minimum value to be added so that array becomes balanced.\nGiven an array of even size, task is to find minimum value that can be added to an element so that array become balanced. An array is balanced if the sum of the left half of the array elements is equal to the sum of right half. Suppose, we have an array 1 3 1 2 4 3. The Sum of first three elements is 1 + 3 + 1 = 5 and sum of last three elements is 2 + 4 + 3 = 9\nSo this is unbalanced, to make it balanced the minimum number we can add is 4 to any element in first half.

“TESTCASE_1”: “4\n2 1 4 6\n###—###SEPERATOR—###—\n7”, “TESTCASE_2”: “5\n2 4 7 31 3\n###—###SEPERATOR—###—\n35”, “TESTCASE_3”: “7\n5 1 4 41 42 8 9\n\n###—###SEPERATOR—###—\n90”, “TESTCASE_4”: “6\n12 15 42 55 31 10\n###—###SEPERATOR—###—\n27”, “TESTCASE_5”: “0\n###—###SEPERATOR—###—\n0

ANSWER

#include <iostream>
using namespace std;
int main()
{ 
  int n,a[100],b[100],c[100],s1=0,s2=0;
  cin>>n;
  for(int i=0;i<n;i++)
  {
    cin>>a[i];
  }
  for(int i=0;i<n;i++)
  {
    if(i<n/2)
    {
      b[i]=a[i];
      s1=s1+b[i];
      
    }
    else if(i>=n/2)
    {
      c[i]=a[i];
      s2=s2+c[i];
      
    }
  }
  
    if(s1>s2)
    {
       cout<<s1-s2;
    }
   else if(s1<s2)
   {
     cout<<s2-s1;
   }
    
	return 0;
}
Ads Blocker Image Powered by Code Help Pro

Ads Blocker Detected!!!

We have detected that you are using extensions to block ads. Please support us by disabling these ads blocker.