Given an array of N elements, the task is to minimize the maximum difference of adjacent elements by inserting at most K elements in the array.
Input: arr = [2, 6, 8] K = 1
After insertion of 4 in between 2 and 6, the array becomes [2, 4, 6, 8]. In this case the maximum difference between any adjacent element is 2, which is the minimum that can be.
Input: arr = [3, 12] K = 2
After insertion of 6 and 9 in between 3 and 12, the array becomes [3, 6, 9, 12]. In this case the maximum difference between any adjacent element is 3, which is the minimum that can be.
Approach: In order to solve this problem, we are using the following Binary Search based approach:
- Find the maximum difference between any two adjacent element in the array and store it in a variable, say worst.
- Search from best(1 initially) to worst and for every mid value find the number of insertions required.
- Whenever the number of insertions is greater than K for a particular value of mid, search between [mid + 1, worst], that is the higher half. Otherwise search between [best, mid-1], that is the lower half to check if the maximum difference can be further minimized with at most K insertions.
- The final worst value after termination of the loop gives the answer.
Below code is the implementation of the above approach:
- Minimize the maximum difference between adjacent elements in an array
- Minimize the maximum absolute difference of adjacent elements in a circular array
- Minimize the difference between minimum and maximum elements
- Maximum sum of difference of adjacent elements
- Maximum length subarray with difference between adjacent elements as either 0 or 1
- Maximum subsequence sum with adjacent elements having atleast K difference in index
- Missing occurrences of a number in an array such that maximum absolute difference of adjacent elements is minimum
- Minimize sum of adjacent difference with removal of one element from array
- Minimize the maximum difference between the heights
- Minimize the maximum minimum difference after one removal from array
- Minimize the difference between the maximum and minimum values of the modified array
- Sort elements of an array in increasing order of absolute difference of adjacent elements
- Maximum sum such that no two elements are adjacent
- Maximum sum such that no two elements are adjacent | Set 2
- Maximum set bit sum in array without considering adjacent elements
If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to firstname.lastname@example.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.