HomeSoftware DevelopmentMaximise distance by rearranging all duplicates at identical distance in given Array

Maximise distance by rearranging all duplicates at identical distance in given Array


Given an array arr[] of N integers. Prepare the array in a means such that the minimal distance amongst all pairs of identical parts is most amongst all attainable preparations. The duty is to search out this most worth.

Examples:

Enter: arr[] = {1, 1, 2, 3}
Output: 3
Rationalization: All attainable preparations are: 
{1, 1, 2, 3}, {1, 1, 3, 2}, {1, 2, 1, 3}, {1, 2, 3, 1}, {1, 3, 1, 2}, {1, 3, 2, 1},  
{2, 1, 1, 3}, {2, 1, 3, 1}, {2, 3, 1, 1}, {3, 1, 1, 2}, {3, 1, 2, 1}, {3, 2, 1, 1}.
Right here the preparations {1, 2, 3, 1} and {1, 3, 2, 1} provides the reply which is 3.
As distance = |(index of first 1) – (index of second 1)|

Enter: arr[] = {1, 2, 1, 2, 9, 10, 9}
Output: 4
Rationalization: One such association is {2, 9, 1, 10, 2, 9, 1}

 

Strategy: The method to resolve this downside relies on the commentary that the parts with most frequency should have as a lot distance between them as attainable. Observe the steps talked about under to resolve the issue: 

  • Discover out the aspect(s) with most frequency.
  • Suppose m parts have most frequency max_freq then conquer m*max_freq positions from the N positions. Now the positions unoccupied are un_pos = N max_freq*m. 
  • Now, group the weather which should not have most frequency consecutively in the identical order and have an equal interval.
  • The best interval will be given by interval = un_pos/(max_freq-1) as a result of when all of the occurrences of m parts are positioned equidistant to one another it’s going to break the association in (max_freq – 1) segments.
  • And at last including m for the best frequency parts one every we get the reply to the given query as interval + m.

Beneath is the implementation of the above method.

C++

#embrace <bits/stdc++.h>

utilizing namespace std;

  

int find_max_distance(vector<int> a, int n)

{

    int m = 0, max_freq = 0;

    int un_pos, interval, reply;

  

    

    

    map<int, int> count_freq;

  

    for (int i = 0; i < n; i++) {

        count_freq[a[i]]++;

        max_freq = max(max_freq,

                       count_freq[a[i]]);

    }

  

    

    

    for (auto iterator : count_freq) {

        if (iterator.second == max_freq)

            m++;

    }

  

    un_pos = n - m * max_freq;

    interval = un_pos / (max_freq - 1);

  

    reply = interval + m;

  

    return reply;

}

  

int primary()

{

    int N = 7;

    vector<int> arr = { 1, 2, 1, 2, 9, 10, 9 };

  

    int consequence = find_max_distance(arr, N);

    cout << consequence;

    return 0;

}

Time Complexity: O(N)
Auxiliary House: O(N)

RELATED ARTICLES

LEAVE A REPLY

Please enter your comment!
Please enter your name here

Most Popular

Recent Comments