![]() |
VOOZH | about |
Given an array arr[] of N integers. Arrange the array in a way such that the minimum distance among all pairs of same elements is maximum among all possible arrangements. The task is to find this maximum value.
Examples:
Input: arr[] = {1, 1, 2, 3}
Output: 3
Explanation: All possible arrangements 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}.
Here the arrangements {1, 2, 3, 1} and {1, 3, 2, 1} gives the answer which is 3.
As distance = |(index of first 1) - (index of second 1)|Input: arr[] = {1, 2, 1, 2, 9, 10, 9}
Output: 4
Explanation: One such arrangement is {2, 9, 1, 10, 2, 9, 1}
Approach: The approach to solve this problem is based on the observation that the elements with maximum frequency must have as much distance between them as possible. Follow the steps mentioned below to solve the problem:
Below is the implementation of the above approach.
4
Time Complexity: O(N)
Auxiliary Space: O(N)