Open In App

Maximize the absolute difference for all elements in the array

Last Updated : 26 Apr, 2024
Improve
Improve
Like Article
Like
Save
Share
Report

Given an array A[] of size N and B[] of size M (M >= N), the task is to construct an array C[] by choosing N integers from B[] such that for every index i, sum of absolute difference between A[i] and C[i] is maximum.

Examples:

Input: N = 4, M = 6, A[] = {6, 1, 2, 4}, B[] = {3, 5, 1, 7, 2, 3}
Output: 16
Explanation: We can choose (1, 5, 7, 2) from B[], so the sum of absolute differences will be D = |6−1| + |1−5| + |2−7| + |4−2| = 5 + 4 + 5 + 2 = 16

Input: N = 5, M = 5, A[] = {1, 2, 3, 4, 5}, B= {1, 2, 3, 4, 5}
Output: 12
Explanation: We cab choose (5,4,3,2,1) from B[], so the sum of absolute differences will be D = |1−5| + |2−4| + |3−3| + |4−2| + |5−1| = 4 + 2 + 0 + 2 + 4 = 12.

Approach: To solve the problem, follow the below idea:

The code aims to maximize the absolute differences between elements of the two arrays by pairing the largest element from the first array with the smallest element from the second array and vice versa. Sort the array A[] in increasing order and B[] in decreasing order. Maintain pointers to mark the start and end of A[] and B[]. The algorithm prioritizes choosing elements that result in larger absolute differences, contributing to the overall sum.

Step-by-step algorithm:

  • Sort A[] in ascending order and B[] in descending order.
  • Initialize variables startA and endA as start and end pointers for array A[] and startB and endB as start and end pointers for array B[].
  • Compare the absolute difference between the elements pointed to by startA and startB, and endA and endB.
  • Increment the sum with the greater absolute difference, and move the pointers accordingly.
  • Repeat the process until cnt reaches n.
  • Print the final sum.

Below is the implementation of the algorithm:

C++
#include <iostream>
#include <vector>
#include <algorithm>

#define MOD 1000000007

using namespace std;

// Function to solve the problem
void solve(vector<long long int>& A,
           vector<long long int>& B, int N, int M)
{

    // Initializing variables and sorting the arrays
    int cnt = 0;
    sort(A.begin(), A.end());
    sort(B.begin(), B.end(), greater<int>());
    int startA = 0, startB = 0, endA = N - 1, endB = M - 1;
    long long int sum = 0;

    // Loop to maximize the absolute differences
    while (cnt < N) {
        if (abs(A[startA] - B[startB])
            > abs(A[endA] - B[endB])) {
            sum += abs(A[startA] - B[startB]);
            startA++;
            startB++;
        }
        else {
            sum += abs(A[endA] - B[endB]);
            endA--;
            endB--;
        }
        cnt++;
    }

    // Print the final sum
    cout << sum << "\n";
}

// Main function
int main()
{
    // Taking input for the number of elements in two arrays
    int N, M;
    N = 4;
    M = 6;

    // Initializing vectors to store elements of the two
    // arrays
    vector<long long int> A(N), B(M);
    A = { 6, 1, 2, 4 };
    B = { 3, 5, 1, 7, 2, 3 };
    solve(A, B, N, M);

    return 0;
}
Java
/*package whatever //do not write package name here */

import java.io.*;
import java.util.Arrays;

public class Main {
    // Function to solve the problem
    static void solve(int[] A, int[] B, int N, int M) {
        int MOD = 1000000007;

        // Initializing variables and sorting the arrays
        int cnt = 0;
        Arrays.sort(A);
        Arrays.sort(B);
        int startA = 0, startB = 0, endA = N - 1, endB = M - 1;
        long sum = 0;

        // Loop to maximize the absolute differences
        while (cnt < N) {
            if (Math.abs(A[startA] - B[startB]) > Math.abs(A[endA] - B[endB])) {
                sum += Math.abs(A[startA] - B[startB]);
                startA++;
                startB++;
            } else {
                sum += Math.abs(A[endA] - B[endB]);
                endA--;
                endB--;
            }
            cnt++;
        }
        // Print the final sum
        System.out.println(sum);
    }
    // Main function
    public static void main(String[] args) {
        // Taking input for the number of elements in two arrays
        int N = 4, M = 6;
        // Initializing arrays to store elements of the two arrays
        int[] A = {6, 1, 2, 4};
        int[] B = {3, 5, 1, 7, 2, 3};
        solve(A, B, N, M);
    }
}
Python3
# Function to solve the problem
def solve(A, B, N, M):
    MOD = 1000000007

    # Initializing variables and sorting the arrays
    cnt = 0
    A.sort()
    B.sort(reverse=True)
    startA, startB, endA, endB = 0, 0, N - 1, M - 1
    sum = 0

    # Loop to maximize the absolute differences
    while cnt < N:
        if abs(A[startA] - B[startB]) > abs(A[endA] - B[endB]):
            sum += abs(A[startA] - B[startB])
            startA += 1
            startB += 1
        else:
            sum += abs(A[endA] - B[endB])
            endA -= 1
            endB -= 1
        cnt += 1

    # Print the final sum
    print(sum)

# Main function
def main():
    # Taking input for the number of elements in two arrays
    N, M = 4, 6

    # Initializing lists to store elements of the two arrays
    A = [6, 1, 2, 4]
    B = [3, 5, 1, 7, 2, 3]
    solve(A, B, N, M)

if __name__ == "__main__":
    main()
C#
using System;
using System.Linq;
using System.Collections.Generic;

class Program
{
    const long MOD = 1000000007;

    // Function to solve the problem
    static void Solve(List<long> A, List<long> B, int N, int M)
    {
        // Initializing variables and sorting the arrays
        int cnt = 0;
        A.Sort();
        B.Sort((a, b) => b.CompareTo(a));
        int startA = 0, startB = 0, endA = N - 1, endB = M - 1;
        long sum = 0;

        // Loop to maximize the absolute differences
        while (cnt < N)
        {
            if (Math.Abs(A[startA] - B[startB]) > Math.Abs(A[endA] - B[endB]))
            {
                sum += Math.Abs(A[startA] - B[startB]);
                startA++;
                startB++;
            }
            else
            {
                sum += Math.Abs(A[endA] - B[endB]);
                endA--;
                endB--;
            }
            cnt++;
        }

        // Print the final sum
        Console.WriteLine(sum);
    }

    // Main function
    static void Main()
    {
        // Taking input for the number of elements in two arrays
        int N = 4, M = 6;

        // Initializing lists to store elements of the two arrays
        List<long> A = new List<long> { 6, 1, 2, 4 };
        List<long> B = new List<long> { 3, 5, 1, 7, 2, 3 };
        Solve(A, B, N, M);
    }
}

// This code is contributed by rambabuguphka
JavaScript
// Function to solve the problem
function solve(A, B, N, M) {
    // Initializing variables and sorting the arrays
    let cnt = 0;
    A.sort((a, b) => a - b);
    B.sort((a, b) => b - a);
    let startA = 0, startB = 0, endA = N - 1, endB = M - 1;
    let sum = 0;

    // Loop to maximize the absolute differences
    while (cnt < N) {
        if (Math.abs(A[startA] - B[startB]) > Math.abs(A[endA] - B[endB])) {
            sum += Math.abs(A[startA] - B[startB]);
            startA++;
            startB++;
        } else {
            sum += Math.abs(A[endA] - B[endB]);
            endA--;
            endB--;
        }
        cnt++;
    }

    // Print the final sum
    console.log(sum);
}

// Main function
function main() {
    // Taking input for the number of elements in two arrays
    let N = 4;
    let M = 6;

    // Initializing arrays to store elements of the two arrays
    let A = [6, 1, 2, 4];
    let B = [3, 5, 1, 7, 2, 3];
    solve(A, B, N, M);
}

// Call the main function
main();

Output
16





Time Complexity: O(N log N + M * logM), where N is the length of input array A[] and M is the length of input array B[].
Auxiliary Space: O(N)

Approach 2 :

  • Sort both arrays A[] and B[].
  • Define a 2D dynamic programming table dp[][] where dp[i][j] represents the maximum sum of the absolute differences possible when considering the first i elements from the A[] and first j elements from the B[].
  • Initialize dp[][] with the zeros.
  • Iterate over the elements of A[] and B[] and update the dp[][] table based on the current elements being considered.
  • The recurrence relation for the updating dp[i][j] would be:
  • dp[i][j] = max(dp[i][j], dp[i-1][j-1] + abs(A[i-1] – B[j-1]))
  • Finally, the maximum sum of absolute differences will be stored in the dp[N][M] where N is the size of the A[] and M is the size of B[].

This approach effectively considers all possible combinations of the choosing elements from the arrays A[] and B[] and calculates the maximum sum of the absolute differences.

Example :

C++
#include <iostream>
#include <vector>
#include <algorithm>
#include <cmath>

int GFG(int N, int M, std::vector<int>& A, std::vector<int>& B) {
    // Sort vectors A and B
    std::sort(A.begin(), A.end());
    std::sort(B.begin(), B.end(), std::greater<int>());

    // Initialize a 2D DP table
    std::vector<std::vector<int>> dp(N+1, std::vector<int>(M+1, 0));

    // Iterate over each element of the A and B
    for (int i = 1; i <= N; ++i) {
        for (int j = 1; j <= M; ++j) {
            // Update dp[i][j] based on current elements being considered
            dp[i][j] = std::max(dp[i][j], dp[i-1][j-1] + std::abs(A[i-1] - B[j-1]));
        }
    }

    return dp[N][M];
}

int main() {
    // Example usage:
    int N = 4;
    int M = 6;
    std::vector<int> A = {6, 1, 2, 4};
    std::vector<int> B = {3, 5, 1, 7, 2, 3};
    std::cout << GFG(N, M, A, B) << std::endl;

    N = 5;
    M = 5;
    A = {1, 2, 3, 4, 5};
    B = {1, 2, 3, 4, 5};
    std::cout << GFG(N, M, A, B) << std::endl;

    return 0;
}
Java
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;

public class Main {
    static int GFG(int N, int M, ArrayList<Integer> A, ArrayList<Integer> B) {
        // Sort arrays A and B
        Collections.sort(A);
        Collections.sort(B, Collections.reverseOrder());

        // Initialize a 2D DP table
        int[][] dp = new int[N + 1][M + 1];

        // Iterate over each element of A and B
        for (int i = 1; i <= N; ++i) {
            for (int j = 1; j <= M; ++j) {
                // Update dp[i][j] based on current elements being considered
                dp[i][j] = Math.max(dp[i][j], dp[i - 1][j - 1] + Math.abs(A.get(i - 1) - B.get(j - 1)));
            }
        }

        return dp[N][M];
    }

    public static void main(String[] args) {
        // Example usage:
        int N = 4;
        int M = 6;
        ArrayList<Integer> A = new ArrayList<>(Arrays.asList(6, 1, 2, 4));
        ArrayList<Integer> B = new ArrayList<>(Arrays.asList(3, 5, 1, 7, 2, 3));
        System.out.println(GFG(N, M, A, B)); // Output: 10

        N = 5;
        M = 5;
        A = new ArrayList<>(Arrays.asList(1, 2, 3, 4, 5));
        B = new ArrayList<>(Arrays.asList(1, 2, 3, 4, 5));
        System.out.println(GFG(N, M, A, B)); // Output: 12
    }
}
Python
def GFG(N, M, A, B):
    A.sort()
    B.sort(reverse=True)  
    # Initialize a 2D DP table
    dp = [[0] * (M+1) for _ in range(N+1)]
    # Iterate over each element of the A and B
    for i in range(1, N+1):
        for j in range(1, M+1):
            # Update dp[i][j] based on current elements being considered
            dp[i][j] = max(dp[i][j], dp[i-1][j-1] + abs(A[i-1] - B[j-1]))

    return dp[N][M]
# Example usage:
N = 4
M = 6
A = [6, 1, 2, 4]
B = [3, 5, 1, 7, 2, 3]
print(GFG(N, M, A, B))
N = 5
M = 5
A = [1, 2, 3, 4, 5]
B = [1, 2, 3, 4, 5]
print(GFG(N, M, A, B))
JavaScript
function GFG(N, M, A, B) {
    // Sort arrays A and B
    A.sort((a, b) => a - b);
    B.sort((a, b) => b - a);

    // Initialize a 2D DP table
    let dp = new Array(N + 1).fill(0).map(() => new Array(M + 1).fill(0));

    // Iterate over each element of A and B
    for (let i = 1; i <= N; ++i) {
        for (let j = 1; j <= M; ++j) {
            // Update dp[i][j] based on current elements being considered
            dp[i][j] = Math.max(dp[i][j], dp[i - 1][j - 1] + Math.abs(A[i - 1] - B[j - 1]));
        }
    }

    return dp[N][M];
}

// Example usage:
let N = 4;
let M = 6;
let A = [6, 1, 2, 4];
let B = [3, 5, 1, 7, 2, 3];
console.log(GFG(N, M, A, B));

N = 5;
M = 5;
A = [1, 2, 3, 4, 5];
B = [1, 2, 3, 4, 5];
console.log(GFG(N, M, A, B));

output :

10
12

Time Complexity: O(N×M)

Auxiliary Space: O(N×M)




Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads