- Trending Categories
- Data Structure
- Networking
- RDBMS
- Operating System
- Java
- iOS
- HTML
- CSS
- Android
- Python
- C Programming
- C++
- C#
- MongoDB
- MySQL
- Javascript
- PHP

- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who

In this problem, we are given an array arr[] of n elements that represent N index positions and there are C magnets. Our task is to print all these magnets in such a way that the distance between the two nearest magnets is as large as possible.

Let’s take an example to understand the problem,

**Input** − array = { 1, 4, 6,12, 28, 44 } C = 4

**Output** − 11

To solve this problem, we will use a binary search to maximum distance. We will fix a maximum distance and then placing all magnets between 0 to maximum distance is valid.

Then we will apply a binary search to find middle values and check if placing magnets is possible. If yes then place magnet and treat mid as max distance and follow the same procedure.

Program to show an implementation of our solution,

#include <iostream> using namespace std; bool canPlace(int arr[], int n, int C, int mid){ int magnet = 1, currPosition = arr[0]; for (int i = 1; i < n; i++) { if (arr[i] - currPosition >= mid) { magnet++; currPosition = arr[i]; if (magnet == C) return true; } } return false; } int minDistMax(int n, int C, int arr[]){ int lo, hi, mid, ans; lo = 0; hi = arr[n - 1]; ans = 0; while (lo <= hi) { mid = (lo + hi) / 2; if (!canPlace(arr, n, C, mid)) hi = mid - 1; else { ans = max(ans, mid); lo = mid + 1; } } return ans; } int main(){ int C = 4; int arr[] = { 1, 4, 6,12, 28, 44 }; int n = sizeof(arr) / sizeof(arr[0]); cout<<"Maximised Minimum distance is "<<minDistMax(n, C, arr); return 0; }

Maximised Minimum distance is 11

- Related Questions & Answers
- Place k elements such that minimum distance is maximized in C++
- Count of pairs of (i, j) such that ((n % i) % j) % n is maximized in C++
- Pick maximum sum M elements such that contiguous repetitions do not exceed K in C++
- Sort array of points by ascending distance from a given point JavaScript
- Find minimum sum such that one of every three consecutive elements is taken in C++
- Find minimum x such that (x % k) * (x / k) == n in C++
- Rearrange an array such that arr[i] = i in C++
- C program to calculate distance between two points
- Count pairs in an array such that at least one element is prime in C++
- Find minimum radius such that atleast k point lie inside the circle in C++
- Maximum sum from three arrays such that picking elements consecutively from same is not allowed in C++
- JavaScript - How to pick random elements from an array?
- Minimum Time Visiting All Points in C++
- Find largest d in array such that a + b + c = d in C++
- Find number of pairs in an array such that their XOR is 0 using C++.

Advertisements