make the full circular path, shortest path exercise?

后端 未结 8 1546
耶瑟儿~
耶瑟儿~ 2021-02-04 22:27

I got this question in an interview and I was not able to solve it.

You have a circular road, with N number of gas stations. You know the ammount of gas

8条回答
  •  旧时难觅i
    2021-02-04 23:09

    If we define that a trip from station A to B comprises of the GasAtStation A and TripCost. Then for each trip we have that TripBalance = GasAtStation-TripCost

    The sum of all the trip balances must be greater or equal to zero, otherwise a solution does not exist. The solution consists of having a list with the trip balances for each gas station and iterate through the items keeping a variable for the tripBalance, if the tripBalance becomes negative, then the trip should start at the next gas station, if so, we reset the tripBalance and we keep processing until we check the last entry in the list:

    public int FindFirstStation(List tripBalances)
    {
      if (tripBalances.Sum() < 0) return -1;
      var firstStation = 0;
      var tripBalance = 0;
    
      for (int i = 0; i < tripBalances.Count; i++)
      {
        tripBalance += tripBalances[i];
        if (tripBalance < 0)
        {
          tripBalance = 0;
          firstStation = i + 1; // next station
        }
      }
      return firstStation;
    }
    

    I tested it using the following code:

    [TestMethod]
    public void Example()
    {
      var tripBalances = new List { 0, 1, -2, 3 };
      var resolver = new GasStationResolver();
      var indexOfGasStation = resolver.FindFirstStation(tripBalances);
      Assert.AreEqual(3, indexOfGasStation);
    }
    

    See that the passed values are the ones worked out from the example given at the question header. In this case, the answer is that the last gas station in our list should be the first gas station. Finally, if there is not solution, the method returns -1.

    Another example to cover where the stations with higher gas are not the solution:

    /// 
    /// Station 1 - Gas: 3   Cost: 4
    /// Station 2 - Gas: 10  Cost: 11
    /// Station 3 - Gas: 8   Cost: 9
    /// Station 4 - Gas: 6   Cost: 3
    /// Station 5 - Gas: 4   Cost: 2
    /// 
    /// Then - Trip Balances are:
    /// Station 1 - -1
    /// Station 2 - -1
    /// Station 3 - -1
    /// Station 4 -  3
    /// Station 5 -  2
    /// 
    [TestMethod]    
    public void SecondExample()
    {
      var tripBalances = new List { -1, -1, -1, 3, 2 };
      var resolver = new GasStationResolver();
      var indexOfGasStation = resolver.FindFirstStation(tripBalances);
      Assert.AreEqual(3, indexOfGasStation);
    }
    

提交回复
热议问题