Minimize Max Distance to Gas Station — LeetCode 774 Python Solution
HardLeetCode PremiumArrayBinary Search
- Problem
- #774
- Pattern
- Monotonic Stack
- Reading time
- 2 min
- Source
- leetcode.com
The problem
You are given an integer array stations that represents the positions of the gas stations on the x-axis. You are also given an integer k.
Example
- Input
- stations = [1,2,3,4,5,6,7,8,9,10], k = 9
- Output
- 0.50000
Python solution
Python
class Solution:
def minmaxGasDist(self, stations: List[int], k: int) -> float:
def check(x):
return sum(int((b - a) / x) for a, b in pairwise(stations)) <= k
left, right = 0, 1e8
while right - left > 1e-6:
mid = (left + right) / 2
if check(mid):
right = mid
else:
left = mid
return leftComplexity
| Measure | Complexity |
|---|---|
| Time | O(log n) or O(n log n) |
| Space | O(1) auxiliary |
Pattern: Monotonic Stack
Answer "what is the next greater element" for every position in one pass. LeetCode 774. Minimize Max Distance to Gas Station is filed here because the reference solution below belongs to the algorithm family this hub collects, even though its LeetCode tags point elsewhere.
The monotonic stack guide has the Python template for the pattern and the 225 LeetCode problems that use it.
Related problems
Frequently asked questions
- How hard is LeetCode 774. Minimize Max Distance to Gas Station?
- LeetCode 774. Minimize Max Distance to Gas Station is rated Hard on LeetCode.
- What topics does LeetCode 774. Minimize Max Distance to Gas Station cover?
- LeetCode 774. Minimize Max Distance to Gas Station is tagged Array and Binary Search on LeetCode.
- Is LeetCode 774. Minimize Max Distance to Gas Station a premium problem?
- Yes. LeetCode 774. Minimize Max Distance to Gas Station is a LeetCode Premium problem, so the full statement and test cases require a paid LeetCode subscription.