# C++ program to check whether we can distribute bags so that two friends will get same amount of candies

C++Server Side ProgrammingProgramming

Suppose we have an array A with 4 elements. There are 4 bags of candies, ith bag contains A[i] amount of candies. We want to give each bags to one of our two friends. We have to check whether we can distribute these bags in such a way that each friend receives the same amount of candies in total?

So, if the input is like A = [1, 7, 11, 5], then the output will be True, because we can give the first and the third bag to the first friend, and the second and the fourth bag to the second friend. This way, each friend will receive 12 candies.

## Steps

To solve this, we will follow these steps −

a := A[0]
b := A[1]
c := A[2]
d := A[3]
if (a + b) is same as (c + d) or (a + c) is same as (b + d) or (a + d) is same as (b + c) or (a + b + c) is same as d or (a + b + d) is same as c or (a + c + d) is same as b or (b + c + d) is same as a, then:
return true
Otherwise
return false

## Example

Let us see the following implementation to get better understanding −

#include <bits/stdc++.h>
using namespace std;

bool solve(vector<int> A) {
int a = A[0];
int b = A[1];
int c = A[2];
int d = A[3];
if (a + b == c + d || a + c == b + d || a + d == b + c || a + b + c == d || a + b + d ==          c || a + c + d == b || b + c + d == a)
return true;
else
return false;
}
int main() {
vector<int> A = { 1, 7, 11, 5 };
cout << solve(A) << endl;
}

## Input

1, 7, 11, 5

## Output

1
Updated on 03-Mar-2022 07:01:58