- 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

# Place k elements such that minimum distance is maximized in C++

In this problem, we are given an array of n points that lie on the same line. Our task is to place k elements of the array in such a way that the minimum distance between them is maximized.

Let’s take an example to understand the problem,

**Input** − array = {}

**Output** −

To solve this problem, we will find have to find the maximum possible minimum distance. For such a problem first, we need to sort the given array and then do a binary search until we get the solution at mid.

## Example

Program to show the implementation of our solution,

#include <bits/stdc++.h> using namespace std; bool canGenerateResult(int mid, int arr[], int n, int k) { int pos = arr[0]; int elements = 1; for (int i=1; i<n; i++){ if (arr[i] - pos >= mid){ pos = arr[i]; elements++; if (elements == k) return true; } } return 0; } int maxMinDist(int arr[], int n, int k) { sort(arr,arr+n); int res = -1; int left = arr[0], right = arr[n-1]; while (left < right){ int mid = (left + right)/2; if (canGenerateResult(mid, arr, n, k)){ res = max(res, mid); left = mid + 1; } else right = mid; } return res; } int main() { int arr[] = {3, 5, 6, 9, 1, 8}; int n = sizeof(arr)/sizeof(arr[0]); int k = 3; cout<<"The maximized minimum distance is : "<<maxMinDist(arr, n, k); return 0; }

## Output

The maximized minimum distance is : 4

- Related Questions & Answers
- Pick points from array such that minimum distance is maximized in C++
- Find minimum x such that (x % k) * (x / k) == n in C++
- Place K-knights such that they do not attack each other in C++
- Maximum value K such that array has at-least K elements that are >= K in C++
- Find minimum sum such that one of every three consecutive elements is taken in C++
- Find minimum radius such that atleast k point lie inside the circle in C++
- Count of pairs of (i, j) such that ((n % i) % j) % n is maximized in C++
- Maximum sum possible for a sub-sequence such that no two elements appear at a distance < K in the array in C++
- Find minimum positive integer x such that a(x^2) + b(x) + c >= k in C++
- Find prime number K in an array such that (A[i] % K) is maximum in C++
- Pick maximum sum M elements such that contiguous repetitions do not exceed K in C++
- Maximum sum possible for a sub-sequence such that no two elements appear at a distance < K in the array in C++ program
- Find smallest number K such that K % p = 0 and q % K = 0 in C++
- Python – Remove Elements in K distance with N
- Print direction of moves such that you stay within the [-k, +k] boundary in C++

Advertisements