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++
|
Time Complexity: O(N)
Auxiliary House: O(N)