The Wayback Machine - https://web.archive.org/web/20210513012745/https://www.geeksforgeeks.org/minimum-number-of-swaps-required-to-minimize-sum-of-absolute-differences-between-adjacent-array-elements/
Skip to content
Related Articles

Related Articles

Minimum number of swaps required to minimize sum of absolute differences between adjacent array elements
  • Last Updated : 12 May, 2021

Given an array arr[] consisting of N distinct positive integers, the task is to find the minimum number of elements required to be swapped to minimize the sum of absolute difference of each pair of adjacent elements. 

Examples:

Input: arr[] = {8, 50, 11, 2}
Output: 2
Explanation:
Operation 1: Swapping of elements 8 and 2, modifies the array arr[] to {2, 50, 11, 8}.
Operation 2: Swapping of elements 8 and 50, modifies the array arr[] to {2, 8, 11, 50}.
The sum of absolute difference of adjacent elements of the modified array is 48, which is minimum.
Therefore, the minimum number of swaps required is 2. 

Input: arr[] = {3, 4, 2, 5, 1}
Output: 2

Approach: The given problem can be solved based on the observation that the sum of the absolute difference of adjacent elements will be minimum if the array is either sorted in increasing or decreasing order. Follow the steps to solve the problem.



Below is the implementation of the above approach:

C++




// C++ program for the above approach
  
#include <bits/stdc++.h>
using namespace std;
  
// Comparator to sort in the descending
// order
bool mycmp(pair<int, int> a,
           pair<int, int> b)
{
    return a.first > b.first;
}
  
// Function to find the minimum number
// of swaps required to sort the array
// in increasing order
int minSwapsAsc(vector<int> arr, int n)
{
    // Stores the array elements with
    // its index
    pair<int, int> arrPos[n];
    for (int i = 0; i < n; i++) {
        arrPos[i].first = arr[i];
        arrPos[i].second = i;
    }
  
    // Sort the array in the
    // increasing order
    sort(arrPos, arrPos + n);
  
    // Keeps the track of
    // visited elements
    vector<bool> vis(n, false);
  
    // Stores the count of swaps required
    int ans = 0;
  
    // Traverse array elements
    for (int i = 0; i < n; i++) {
  
        // If the element is already
        // swapped or at correct position
        if (vis[i] || arrPos[i].second == i)
            continue;
  
        // Find out the number of
        // nodes in this cycle
        int cycle_size = 0;
  
        // Update the value of j
        int j = i;
  
        while (!vis[j]) {
            vis[j] = 1;
  
            // Move to the next element
            j = arrPos[j].second;
  
            // Increment cycle_size
            cycle_size++;
        }
  
        // Update the ans by adding
        // current cycle
        if (cycle_size > 0) {
            ans += (cycle_size - 1);
        }
    }
  
    return ans;
}
  
// Function to find the minimum number
// of swaps required to sort the array
// in decreasing order
int minSwapsDes(vector<int> arr, int n)
{
    // Stores the array elements with
    // its index
    pair<int, int> arrPos[n];
  
    for (int i = 0; i < n; i++) {
        arrPos[i].first = arr[i];
        arrPos[i].second = i;
    }
  
    // Sort the array in the
    // descending order
    sort(arrPos, arrPos + n, mycmp);
  
    // Keeps track of visited elements
    vector<bool> vis(n, false);
  
    // Stores the count of resultant
    // swap required
    int ans = 0;
  
    // Traverse array elements
    for (int i = 0; i < n; i++) {
  
        // If the element is already
        // swapped or at correct
        // position
        if (vis[i] || arrPos[i].second == i)
            continue;
  
        // Find out the number of
        // node in this cycle
        int cycle_size = 0;
  
        // Update the value of j
        int j = i;
  
        while (!vis[j]) {
  
            vis[j] = 1;
  
            // Move to the next element
            j = arrPos[j].second;
  
            // Increment the cycle_size
            cycle_size++;
        }
  
        // Update the ans by adding
        // current cycle size
        if (cycle_size > 0) {
            ans += (cycle_size - 1);
        }
    }
  
    return ans;
}
  
// Function to find minimum number of
// swaps required to minimize the sum
// of absolute difference of adjacent
// elements
int minimumSwaps(vector<int> arr)
{
    // Sort in ascending order
    int S1 = minSwapsAsc(arr, arr.size());
  
    // Sort in descending order
    int S2 = minSwapsDes(arr, arr.size());
  
    // Return the minimum value
    return min(S1, S2);
}
  
// Drive Code
int main()
{
    vector<int> arr{ 3, 4, 2, 5, 1 };
    cout << minimumSwaps(arr);
  
    return 0;
}
Output:
2

Time Complexity: O(N * log N)
Auxiliary Space: O(N)

Attention reader! Don’t stop learning now. Get hold of all the important mathematical concepts for competitive programming with the Essential Maths for CP Course at a student-friendly price. To complete your preparation from learning a language to DS Algo and many more,  please refer Complete Interview Preparation Course.

My Personal Notes arrow_drop_up
Recommended Articles
Page :