Maximize the absolute difference for all elements in the array
Last Updated :
26 Apr, 2024
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,