
Input: ‘n' = 7 , ‘k’=6, ‘arr’ = {1,2,3,4,5,6,7}.
Answer: 0.5
Explanation:
We can place 6 gas stations at 1.5, 2.5, 3.5, 4.5, 5.5, 6.5.
Thus the value of 'dist' will be 0.5. It can be shown that we can't get a lower value of 'dist' by placing 6 gas stations.
You will only see 1 or 0 in the output where:
1 represents your answer is correct.
0 represents your answer is wrong.
Answers within 10^-6 of the actual answer will be accepted.
The first line contains two integers, ' n' and 'k', representing the size of the array 'arr' and the number of additional gas stations you need to place.
The second line contains 'n' integers, denoting the array 'arr' elements.
Return the minimum value of 'dist'.
You do not need to print anything. It has already been taken care of. Just implement the given function. 1 will be printed for answers with an error less than 10^-6 from the actual answer and 0 otherwise.
The best position to place a gas station is between the gas stations with the current largest distance between them. So we can repeatedly add a gas station in the current largest interval. To do so we maintain two arrays ‘diff’ and ‘count’ of length ‘N-1’. In the ‘diff’ array we store the distance between the two gas stations in the current interval and in the count array we store the number of gas stations added in the current interval. Thus, the current maximum interval for a gas station would be the interval with the maximum value of ‘diff[i] / count[i]’ .
Following the approach from the greedy method, instead of iterating through all the intervals for every gas station, we can maintain a priority queue of pairs {diff[i] / count[i], i} for the ‘ith’ interval sorted in a decreasing order. Then we can choose the interval at the top of the queue, delete it from the queue. Then we increment the count of the ‘ith’ interval and insert {diff[i] / count[i] , i} back into the queue.
Let’s say there exists a value ‘D’ of ‘Dist’ such that for a value ‘d’ < ‘D’ it is not possible to make the maximum distance between all the adjacent gas stations equal to ‘d’ by adding at most ‘K’ gas stations. As we can see this is a monotonic function and thus we can binary search on it. So we binary search on the value of ‘D’ and check if it’s possible to achieve this value of ‘Dist’ by adding at most ‘K’ gas stations.
Element Count in Ranges
First Digit One
Minimize Maximum Adjacent Distance
Sorted Doubly Linked List to Balanced BST
Minimized Maximum of Products Distributed to Any Store