- 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

# Fair Candy Swap in Python

Suppose A and B are two friends. They have candy bars of different sizes. Here A[i] is the size of the i-th bar of candy owned by A, and B[j] is the size of the j-th bar of candy owned by B.

Since they are friends, they want to exchange one candy bar each so that after the exchange, both A and B have the same total amount of candy. (The total amount of candy a person has is the sum of the sizes of candy bars they have.) We have to return an integer array suppose ans, where ans[0] is the size of the candy bar that A must exchange, and ans[1] is the size of the candy bar that B must exchange. If there are multiple answers, we will return only one of them.

For example, if A = [1, 2] and B = [2, 3], then output will be [1, 2]

To solve this, we will follow these steps −

- Take the difference between the sum of A and sum of B, then divide it by 2, and take the integer part into diff
- convert B into a set
- for i in A
- if i – diff in B, then return [i, i – diff]

## Example

Let us see the following implementation to get better understanding −

class Solution(object): def fairCandySwap(self, A, B): diff = (sum(A) - sum(B))//2 B=set(B) for i in A: if i- diff in B: return [i,i-diff] ob1 = Solution() print(ob1.fairCandySwap([1,2], [2,3]))

## Input

[1,2] [2,3]

## Output

[1,2]

- Related Questions & Answers
- Candy in C++
- Maximum Swap in Python
- Program to find ways to make a fair array in Python
- What is a fair value hedge?
- Swap Consecutive Even Elements in Python
- Differentiate between fair value and market value
- Previous Permutation With One Swap in Python
- What is accounting entries for fair value hedge?
- Pattern After Double, Reverse, and Swap in Python
- Program to swap string characters pairwise in Python
- How to remove swap files using Python?
- How to Swap Two Variables using Python?
- Python Pandas - Swap levels of a MultiIndex
- Program to check whether first player win in candy remove game or not in Python?
- Swap two variables in one line in using Python?