![]() |
VOOZH | about |
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:
2
Time Complexity: O(N * log N), The time complexity of this code is O(Nl*ogN), where N is the size of the array. The reason behind this time complexity is due to the sorting algorithm used to sort the array. The code uses the built-in sort() function to sort the array elements in both ascending and descending order. The time complexity of the sort() function is O(N*logN), which dominates the overall time complexity of the code.
Auxiliary Space: O(N), The space complexity of this code is O(N). The reason behind this space complexity is due to the usage of two additional data structures - vector<bool> vis(n, false) and pair<int, int> arrPos[n]. The vis vector is used to keep track of visited elements during the traversal of the array, and arrPos is used to store the index and value of each element in the array. Both of these data structures have a space complexity of O(N). Therefore, the overall space complexity of the code is O(N).