Open In App

Maximize the value left after reducing the Arrays based on given conditions

Last Updated : 24 Mar, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

Given three arrays arr1[], arr2[] and arr3[] of integers, the task is to find the maximum value left in an array after performing the following operation, where in each operation:

  • Select an element (y) from one array and remove that from the array.
  • Subtract y from another element(x) of another array.

Note: If there are multiple occurrences of these numbers, remove/replacement is performed on only one occurrence.

Examples:

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

 

Approach:  It can be solved on the basis of the following observation. 

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.

Now, to minimize either of the above two cases – 
1st Case: Choose the two smallest numbers such that they both appear in different sets to be at odd depth.
2nd Case:  Choose all numbers from the sets where the sum of the numbers is minimum to be at odd depth.

Below is the implementation of the above approach:

C++




// C++ program for the above approach
#include <bits/stdc++.h>
using namespace std;
  
#define N 10000
#define INF 1e9
  
int solve(vector<int>& arr1, vector<int>& arr2,
          vector<int>& arr3)
{
    int a = arr1.size(), b = arr2.size(),
        c = arr3.size();
    vector<int> sum(3), mini(3, INF);
  
    // Calculating sum and minimum element
    // for each array
    for (int i = 0; i < a; i++) {
        sum[0] += arr1[i];
        mini[0] = min(mini[0], arr1[i]);
    }
    for (int i = 0; i < b; i++) {
        sum[1] += arr2[i];
        mini[1] = min(mini[1], arr2[i]);
    }
    for (int i = 0; i < c; i++) {
        sum[2] += arr3[i];
        mini[2] = min(mini[2], arr3[i]);
    }
  
    // Total of all the arrays
    int total = sum[0] + sum[1] + sum[2];
  
    sort(sum.begin(), sum.end());
    sort(mini.begin(), mini.end());
  
    // As first two minimum is
    // already counted in the total,
    // thus they are removed twice
    // and the other choice was
    // with the minimum sum,
    // so, similarly removing it twice.
    int result = max(total - 2 * (mini[0] + mini[1]),
                     total - 2 * (sum[0]));
    return result;
}
  
// Driver Code
int main()
{
    vector<int> arr1 = { 7, 5, 4 };
    vector<int> arr2 = { 2, 9 };
    vector<int> arr3 = { 7, 1 };
  
    cout << solve(arr1, arr2, arr3);
    return 0;
}


Java




// Java program for the above approach
import java.util.*;
public class GFG {
  
    static int solve(int[] arr1, int[] arr2,
                     int[] arr3)
    {
        int a = arr1.length, b = arr2.length,
            c = arr3.length;
  
        int[] sum = new int[3];
        int[] mini = new int[3];
  
        for (int i = 0; i < 3; i++) {
            mini[i] = Integer.MAX_VALUE;
        }
  
        // Calculating sum and minimum element
        // for each array
        for (int i = 0; i < a; i++) {
            sum[0] += arr1[i];
            mini[0] = Math.min(mini[0], arr1[i]);
        }
        for (int i = 0; i < b; i++) {
            sum[1] += arr2[i];
            mini[1] = Math.min(mini[1], arr2[i]);
        }
        for (int i = 0; i < c; i++) {
            sum[2] += arr3[i];
            mini[2] = Math.min(mini[2], arr3[i]);
        }
  
        // Total of all the arrays
        int total = sum[0] + sum[1] + sum[2];
  
        Arrays.sort(sum);
        Arrays.sort(mini);
  
        // As first two minimum is
        // already counted in the total,
        // thus they are removed twice
        // and the other choice was
        // with the minimum sum,
        // so, similarly removing it twice.
        int result = Math.max(total - 2 * (mini[0] + mini[1]),
                              total - 2 * (sum[0]));
        return result;
    }
  
    // Driver Code
    public static void main(String args[])
    {
        int[] arr1 = { 7, 5, 4 };
        int[] arr2 = { 2, 9 };
        int[] arr3 = { 7, 1 };
  
        System.out.println(solve(arr1, arr2, arr3));
    }
}
  
// This code is contributed by Samim Hossain Mondal.


Python3




import math
  
def solve(arr1, arr2, arr3):
    a = len(arr1)
    b = len(arr2)
    c = len(arr3)
    sum = [0, 0, 0]
    infi = math.inf
    mini = [infi, infi, infi]
  
    # Calculating sum and minimum element
    # for each array
    for i in range(0, a):
        sum[0] += arr1[i]
        mini[0] = min(mini[0], arr1[i])
  
    for i in range(0, b):
        sum[1] += arr2[i]
        mini[1] = min(mini[1], arr2[i])
  
    for i in range(0, c):
        sum[2] += arr3[i]
        mini[2] = min(mini[2], arr3[i])
  
    # Total of all the arrays
    total = sum[0] + sum[1] + sum[2]
    sum.sort()
    mini.sort()
  
    # As first two minimum is already counted in the total,
    # thus they are removed twice and 
    # the other choice was with the minimum sum, 
    # so, similarly removing it twice.
    result = max(total - 2 * (mini[0] + mini[1]), total - 2 * (sum[0]))
    return result
  
print(solve([7, 5, 4], [2, 9], [7, 1]))
  
# This code is contributed by abhinavprkash.


C#




// C# program for the above approach
using System;
using System.Collections;
  
class GFG {
  
    static int solve(int[] arr1, int[] arr2,
                     int[] arr3)
    {
        int a = arr1.Length, b = arr2.Length,
            c = arr3.Length;
  
        int[] sum = new int[3];
        int[] mini = new int[3];
  
        for (int i = 0; i < 3; i++) {
            mini[i] = Int32.MaxValue;
        }
  
        // Calculating sum and minimum element
        // for each array
        for (int i = 0; i < a; i++) {
            sum[0] += arr1[i];
            mini[0] = Math.Min(mini[0], arr1[i]);
        }
        for (int i = 0; i < b; i++) {
            sum[1] += arr2[i];
            mini[1] = Math.Min(mini[1], arr2[i]);
        }
        for (int i = 0; i < c; i++) {
            sum[2] += arr3[i];
            mini[2] = Math.Min(mini[2], arr3[i]);
        }
  
        // Total of all the arrays
        int total = sum[0] + sum[1] + sum[2];
  
        Array.Sort(sum);
        Array.Sort(mini);
  
        // As first two minimum is
        // already counted in the total,
        // thus they are removed twice
        // and the other choice was
        // with the minimum sum,
        // so, similarly removing it twice.
        int result = Math.Max(total - 2 * (mini[0] + mini[1]),
                              total - 2 * (sum[0]));
        return result;
    }
  
    // Driver Code
    public static void Main()
    {
        int[] arr1 = { 7, 5, 4 };
        int[] arr2 = { 2, 9 };
        int[] arr3 = { 7, 1 };
        Console.Write(solve(arr1, arr2, arr3));
    }
}
// This code is contributed by Samim Hossain Mondal.


Javascript




<script>
// Javascript program for the above approach
  
function solve(arr1, arr2, arr3)
{
    let a = arr1.length, b = arr2.length, 
    c = arr3.length;
    let sum = [], mini = [];
      
    for(let i = 0; i < 3; i++) {
        sum[i] = 0;
    }
    for(let i = 0; i < 3; i++) {
        mini[i] = Number.MAX_SAFE_INTEGER;
    }
  
    // Calculating sum and minimum element 
    // for each array
    for (let i = 0; i < a; i++) {
        sum[0] += arr1[i];
        mini[0] = Math.min(mini[0], arr1[i]);
    }
    for (let i = 0; i < b; i++) {
        sum[1] += arr2[i];
        mini[1] = Math.min(mini[1], arr2[i]);
    }
    for (let i = 0; i < c; i++) {
        sum[2] += arr3[i];
        mini[2] = Math.min(mini[2], arr3[i]);
    }
      
    // Total of all the arrays
    let total = sum[0] + sum[1] + sum[2];
      
  
    sum.sort();
    mini.sort();
      
    // As first two minimum is 
    // already counted in the total, 
    // thus they are removed twice
    // and the other choice was 
    // with the minimum sum,
    // so, similarly removing it twice.
    let result = Math.max(total - 
                     2 * (mini[0] + 
                          mini[1]),
                     total - 2 * (sum[0]));
    return result;
}
  
// Driver Code
let arr1 = [ 7, 5, 4 ];
let arr2 = [ 2, 9 ];
let arr3 = [ 7, 1 ];
  
document.write(solve(arr1, arr2, arr3));
  
// This code is contributed by Samim Hossain Mondal.
</script>


 
 

Output

29

Time Complexity: O(N) Where N is the average size of the arrays 
Auxiliary Space: O(1) 



Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads