Skip to content
geeksforgeeks
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Tutorials
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
  • Practice
    • Build your AI Agent
    • GfG 160
    • Problem of the Day
    • Practice Coding Problems
    • GfG SDE Sheet
  • Contests
    • Accenture Hackathon (Ending Soon!)
    • GfG Weekly [Rated Contest]
    • Job-A-Thon Hiring Challenge
    • All Contests and Events
  • DSA
  • Interview Questions on Array
  • Practice Array
  • MCQs on Array
  • Tutorial on Array
  • Types of Arrays
  • Array Operations
  • Subarrays, Subsequences, Subsets
  • Reverse Array
  • Static Vs Arrays
  • Array Vs Linked List
  • Array | Range Queries
  • Advantages & Disadvantages
Open In App
Next Article:
Maximize count of distinct elements possible in an Array from the given operation
Next article icon

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

Last Updated : 25 Feb, 2022
Comments
Improve
Suggest changes
Like Article
Like
Report

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: 

  • Find out the element(s) with maximum frequency.
  • Suppose m elements have maximum 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 elements which do not have maximum frequency consecutively in the same order and have an equal interval.
  • The greatest interval can be given by interval = un_pos/(max_freq-1) because when all the occurrences of m elements are placed equidistant to each other it will break the arrangement in (max_freq – 1) segments.
  • And finally adding m for the highest frequency elements one each we get the answer to the given question as interval + m.

Below is the implementation of the above approach.

C++




// C++ code to implement the above approach
#include <bits/stdc++.h>
using namespace std;
 
// Function to find
// the maximum possible minimum distance
int find_max_distance(vector<int> a, int n)
{
    int m = 0, max_freq = 0;
    int un_pos, interval, answer;
 
    // To count frequency of
    // each integer value of array
    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]]);
    }
 
    // Loop to find the number of integers
    // in array with maximum frequency
    for (auto iterator : count_freq) {
        if (iterator.second == max_freq)
            m++;
    }
 
    un_pos = n - m * max_freq;
    interval = un_pos / (max_freq - 1);
 
    answer = interval + m;
 
    return answer;
}
 
// Driver Code
int main()
{
    int N = 7;
    vector<int> arr = { 1, 2, 1, 2, 9, 10, 9 };
 
    int result = find_max_distance(arr, N);
    cout << result;
    return 0;
}
 
 

Java




// JAVA code to implement the above approach
import java.util.*;
class GFG
{
   
  // Function to find
  // the maximum possible minimum distance
  public static int find_max_distance(int[] a, int n)
  {
    int m = 0, max_freq = 0;
    int un_pos, interval, answer;
 
    // To count frequency of
    // each integer value of array
    HashMap<Integer, Integer> count_freq
      = new HashMap<>();
 
    for (int i = 0; i < n; i++) {
      if (count_freq.containsKey(a[i])) {
        count_freq.put(a[i],
                       count_freq.get(a[i]) + 1);
      }
      else {
        count_freq.put(a[i], 1);
      }
      max_freq
        = Math.max(max_freq, count_freq.get(a[i]));
    }
 
    // Loop to find the number of integers
    // in array with maximum frequency
    for (Map.Entry<Integer, Integer> iterator :
         count_freq.entrySet()) {
      if (iterator.getValue() == max_freq)
        m++;
    }
 
    un_pos = n - m * max_freq;
    interval = un_pos / (max_freq - 1);
 
    answer = interval + m;
 
    return answer;
  }
 
  // Driver Code
  public static void main(String[] args)
  {
    int N = 7;
    int[] arr = new int[] { 1, 2, 1, 2, 9, 10, 9 };
 
    int result = find_max_distance(arr, N);
    System.out.print(result);
  }
}
 
// This code is contributed by Taranpreet
 
 

Python3




# Python code to implement the above approach
# Function to find
# the maximum possible minimum distance
def find_max_distance(a, n):
    m = 0
    max_freq = 0
    un_pos = 0
    interval = 0
    answer = 0
 
    # To count frequency of
    # each integer value of array
    count_freq = {}
 
    for i in range(n):
        if a[i] not in count_freq:
            count_freq[a[i]] = 1
        else:
            count_freq[a[i]] += 1
        max_freq = max(max_freq,count_freq[a[i]])
     
 
    # Loop to find the number of integers
    # in array with maximum frequency
    for i in count_freq:
        if (count_freq[i] == max_freq):
            m += 1
     
    un_pos = n - m * max_freq
    interval = un_pos // (max_freq - 1)
 
    answer = interval + m
 
    return answer
 
# Driver Code
N = 7
arr =  [1, 2, 1, 2, 9, 10, 9]
result = find_max_distance(arr, N)
print(result)
 
# This code is contributed by rohitsingh07052.
 
 

C#




// C# code to implement the above approach
using System;
using System.Collections.Generic;
class GFG {
 
  // Function to find
  // the maximum possible minimum distance
  public static int find_max_distance(int[] a, int n)
  {
    int m = 0, max_freq = 0;
    int un_pos = 0, interval = 0, answer = 0;
 
    // To count frequency of
    // each integer value of array
    Dictionary<int, int> count_freq
      = new Dictionary<int, int>();
 
    for (int i = 0; i < n; i++) {
      if (count_freq.ContainsKey(a[i])) {
        count_freq[a[i]] = count_freq[a[i]] + 1;
      }
      else {
        count_freq.Add(a[i], 1);
      }
      max_freq = Math.Max(max_freq, count_freq[a[i]]);
    }
 
    // Loop to find the number of integers
    // in array with maximum frequency
    foreach(
      KeyValuePair<int, int> iterator in count_freq)
    {
      if (iterator.Value == max_freq)
        m++;
    }
 
    un_pos = n - m * max_freq;
    interval = un_pos / (max_freq - 1);
 
    answer = interval + m;
 
    return answer;
  }
 
  // Driver Code
  public static void Main()
  {
    int N = 7;
    int[] arr = new int[] { 1, 2, 1, 2, 9, 10, 9 };
 
    int result = find_max_distance(arr, N);
    Console.Write(result);
  }
}
 
// This code is contributed by Samim Hossain Mondal.
 
 

Javascript




<script>
    // JavaScript code to implement the above approach
 
    // Function to find
    // the maximum possible minimum distance
    const find_max_distance = (a, n) => {
        let m = 0, max_freq = 0;
        let un_pos, interval, answer;
 
        // To count frequency of
        // each integer value of array
        let count_freq = {};
 
        for (let i = 0; i < n; i++) {
            if (a[i] in count_freq) count_freq[a[i]]++;
            else count_freq[a[i]] = 1;
            max_freq = Math.max(max_freq,
                count_freq[a[i]]);
        }
 
        // Loop to find the number of integers
        // in array with maximum frequency
        for (let iterator in count_freq) {
            if (count_freq[iterator] == max_freq)
                m++;
        }
 
        un_pos = n - m * max_freq;
        interval = parseInt(un_pos / (max_freq - 1));
        answer = interval + m;
        return answer;
    }
 
    // Driver Code
    let N = 7;
    let arr = [1, 2, 1, 2, 9, 10, 9];
 
    let result = find_max_distance(arr, N);
    document.write(result);
 
// This code is contributed by rakeshsahni
 
</script>
 
 

 
 

Output
4

 

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

 



Next Article
Maximize count of distinct elements possible in an Array from the given operation
author
zargon
Improve
Article Tags :
  • Arrays
  • DSA
  • Greedy
  • Mathematical
  • array-rearrange
  • frequency-counting
Practice Tags :
  • Arrays
  • Greedy
  • Mathematical

Similar Reads

  • Minimize sum of distinct elements of all prefixes by rearranging Array
    Given an array arr[] with size N, the task is to find the minimum possible sum of distinct elements over all the prefixes of the array that can be obtained by rearranging the elements of the array. Examples: Input: arr[] = {3, 3, 2, 2, 3}, N = 5Output: 7Explanation: The permutation arr[] = {3, 3, 3,
    8 min read
  • Maximize count of corresponding same elements in given Arrays by Rotation
    Given two arrays arr1[] and arr2[] of N integers and array arr1[] has distinct elements. The task is to find the maximum count of corresponding same elements in the given arrays by performing cyclic left or right shift on array arr1[]. Examples: Input: arr1[] = { 6, 7, 3, 9, 5 }, arr2[] = { 7, 3, 9,
    8 min read
  • Maximize count of distinct elements possible in an Array from the given operation
    Given an array A[] of size N, the task is to maximize the count of distinct elements in the array by inserting the absolute differences of the existing array elements. Examples: Input: A[] = {1, 2, 3, 5} Output: 5 Explanation: Possible absolute differences among the array elements are: (2 - 1) = 1 (
    6 min read
  • Maximize sum of given array by rearranging array such that the difference between adjacent elements is atmost 1
    Given an array arr[] consisting of N positive integers, the task is to maximize the sum of the array element such that the first element of the array is 1 and the difference between the adjacent elements of the array is at most 1 after performing the following operations: Rearrange the array element
    7 min read
  • Maximum distance between two 1s in a Binary Array in a given range
    Given a binary array of size N and a range in [l, r], the task is to find the maximum distance between two 1s in this given range.Examples: Input: arr = {1, 0, 0, 1}, l = 0, r = 3 Output: 3 In the given range from 0 to 3, first 1 lies at index 0 and last at index 3. Hence, maximum distance = 3 - 0 =
    14 min read
  • Minimum distance between any special pair in the given array
    Given an array arr[] of N integers, the task is to find the minimum possible absolute difference between indices of a special pair. A special pair is defined as a pair of indices (i, j) such that if arr[i] ? arr[j], then there is no element X (where arr[i] < X < arr[j]) present in between indi
    9 min read
  • Rearrange two given arrays to maximize sum of same indexed elements
    Given two arrays A[] and B[] of size N, the task is to find the maximum possible sum of abs(A[i] – B[i]) by rearranging the array elements. Examples: Input: A[] = {1, 2, 3, 4, 5}, B[] = {1, 2, 3, 4, 5}Output: 12Explanation: One of the possible rearrangements of A[] is {5, 4, 3, 2, 1}. One of the pos
    5 min read
  • Maximize X such that Array can be sorted by swapping elements X distance apart
    Given an input arr[] of length N, Which contains integers from 1 to N in unsorted order. You can apply only one type of operation on arr[] elements': Choose an index i and an integer X and swap Ai with an element that is X distance apart and both the indices are within the boundary of the array. The
    10 min read
  • Maximum distance between two even integers in a given array
    Given an array arr[] having N integers, the task is to find the maximum distance between any two occurrences of even integers. Examples: Input: arr[] = {1, 2, 3, 4, 5, 6, 7}Output: 4Explanation: The distance between arr[1] = 2 and arr[5] = 6 is 4 which is the maximum distance between two even intege
    6 min read
  • Maximize remainder difference between two pairs in given Array
    Given an array arr[] of size N, the task is to find 4 indices i, j, k, l such that 0 <= i, j, k, l < N and the value of arr[i]%arr[j] - arr[k]%arr[l] is maximum. Print the maximum difference. If it doesn't exist, then print -1. Examples: Input: N=8, arr[] = {1, 2, 4, 6, 8, 3, 5, 7}Output: 7Exp
    4 min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences