Minimize Max Distance to Gas Station in C++


Suppose we have one horizontal number line. On that number line, we have gas stations at positions stations[0], stations[1], ..., stations[N-1], where N = size of the stations array. Now, we add K more gas stations so that D, the maximum distance between adjacent gas stations, is minimized. We have to find the smallest possible value of D.

So, if the input is like stations = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10], K = 9, then the output will be 0.5

To solve this, we will follow these steps −

  • Define a function ok(), this will take x, array v,

  • ret := 0

  • for initialize i := 0, when i < size of v, update (increase i by 1), do −

    • ret := ret + ceiling of (v[i + 1] - v[i]) / x

  • return ret

  • From the main method do the following −

  • low := 0

  • n := size of s

  • high := s[n - 1] - s[0]

  • while high - low >= 1e-6, do −

    • mid := (low + high) / 2.0

    • x := ok(mid, s)

    • if x > K, then −

      • low := mid

    • Otherwise

      • high := mid

  • return high

Let us see the following implementation to get better understanding −

Example

 Live Demo

#include <bits/stdc++.h>
using namespace std;
class Solution {
   public:
   int ok(double x, vector <int>& v){
      int ret = 0;
      for (int i = 0; i < v.size() - 1; i++) {
         ret += ceil((v[i + 1] - v[i]) / x) - 1;
      }
      return ret;
   }
   double minmaxGasDist(vector<int>& s, int K) {
      double low = 0;
      int n = s.size();
      double high = s[n - 1] - s[0];
      while (high - low >= 1e-6) {
         double mid = (low + high) / 2.0;
         int x = ok(mid, s);
         if (x > K) {
            low = mid;
         }
         else {
            high = mid;
         }
      }
      return high;
   }
};
main(){
   Solution ob;
   vector<int> v = {1,2,3,4,5,6,7,8,9,10};
   cout << (ob.minmaxGasDist(v, 9));
}

Input

{1,2,3,4,5,6,7,8,9,10}, 9

Output

0.5

Updated on: 11-Jul-2020

1K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements