LeetCode: Minimize Max Distance to Gas Station Posted on August 5, 2019July 26, 2020 by braindenny Minimize Max Distance to Gas Station Similar Problems: CheatSheet: Leetcode For Code Interview CheatSheet: Common Code Problems & Follow-ups Tag: #binarysearch, #math, #float, #monotonicfunc On a horizontal number line, we have gas stations at positions stations[0], stations[1], …, stations[N-1], where N = stations.length. Now, we add K more gas stations so that D, the maximum distance between adjacent gas stations, is minimized. Return the smallest possible value of D. Example: Input: stations = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10], K = 9 Output: 0.500000 Note: stations.length will be an integer in range [10, 2000]. stations[i] will be an integer in range [0, 10^8]. K will be an integer in range [1, 10^6]. Answers within 10^-6 of the true value will be accepted as correct. Github: code.dennyzhang.com Credits To: leetcode.com Leave me comments, if you have better ways to solve. Solution: // https://code.dennyzhang.com/minimize-max-distance-to-gas-station // Basic Ideas: binarysearch // Mononotic function: the bigger K is, the smaller D would be // Complexity: Time O(n*log(m)), Space O(1) import "sort" func isPossible(stations []int, K int, D float64) bool { count := 0 for i:=0; i+1<len(stations); i++ { dis := float64(stations[i+1]-stations[i]) if dis <= D { continue } add := int(dis/D) count += add if float64(add)*D > dis { count++ } } return count <= K } func minmaxGasDist(stations []int, K int) float64 { sort.Ints(stations) left, right := float64(0), float64(stations[len(stations)-1]-stations[0]) // always can find for right-left > 0.000006 { mid := (right-left)/2 + left // F, F, F, T, T, T if isPossible(stations, K, mid) { // left half right = mid } else { // right half left = mid } } return left } Post Views: 0