

- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
C++ program to check whether we can distribute bags so that two friends will get same amount of candies
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
- Related Questions & Answers
- Program to count the number of ways to distribute n number of candies in k number of bags in Python
- Distribute Candies in C++
- Distribute Candies to People in Python
- Program to check whether we can get N queens solution or not in Python
- C# program to check whether two sequences are the same or not
- Program to check whether first player can take more candies than other or not in Python
- What benefits can one get out of tea bags?
- Program to check whether leaves sequences are same of two leaves or not in python
- Program to count number of ways we can distribute coins to workers in Python
- Program to check whether we can make group of two partitions with equal sum or not in Python?
- Program to check whether we can fill square where each row and column will hold distinct elements in Python
- Python program to check whether we can pile up cubes or not
- Maximum number of candies that can be bought in C
- Python Program to Check whether 2 Linked Lists are Same
- Program to check whether we can take all courses or not in Python
Advertisements