Input: arr1[] = {1, 2 }
arr2[] = {6, 3, 4 , 5}
arr3[]= {5}
Output: 20
Explanation : Select number 1 from 1st Array and 6 from 2nd Array, (x = 1, y = 6)
1st Array Becomes [(1-6), 2] = [-5, 2]
2nd Array Becomes [3, 4, 5], 3rd Array is the same [5].
Then, choose -5 from 1st Array and 5 from 2nd Array (x = -5, y = 5),
1st Array = [(-5-5), 2] => [-10, 2], 2nd Array = [3, 4], 3rd Array = [5].
Now, choose 5 from 3rd Array and -10 from 1st Array (x = 5, y = -10)
1st Array = [2], 2nd Array = [3, 4], 3rd Array = [5-(-10)] => [15].
Select 2 from 1st Array and 3 from 2nd Array (x = 2, y = 3),
1st Array = [(2-3)] => [-1], 2nd Array = [4], 3rd Array = [15].
Choose -1 from 1st Array and 4 from 2nd Array (x = -1, y = 4)
1st Array = [(-1-4)] => [-5], 2nd Array = [], 3rd Array = [15].
At last, choose 15 from 3rd Array and -5 from 1st Array (x = 15, y = -5)
1st Array = [], 2nd Array = [], 3rd Array = [(15-(-5)] => [20] .
Input: arr1[] = {7, 5, 4}
arr2[] = {2, 9}
arr3[] = {7, 1}
Output: 29
The given problem can be considered as a graph.
There are 3 nodes, where edges between 2 nodes represent an operation and thus show that an edge exists between them.
A directed edge from y to x means that y is removed and x is replaced by x−y.
As in a rooted tree, operations are performed in a way on a leaf, and its parent and leaf are removed.
The whole process continues till the root node is left.
Thus, the final answer is calculated as the difference of sum of elements on even levels and sums on odd levels.
But, the graph would be valid if elements at the odd level are
- from two different sets
- contains all elements from one set.