HardNo. 0774LeetCode Premium
Minimize Max Distance to Gas Station — LeetCode 774 Python Solution
- Pattern
- Monotonic Stack
- Topics
- Array, Binary Search
- 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
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
- Time
- O(log n) or O(n log n)
- Space · auxiliary
- O(1)
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
| No. | Problem | Difficulty |
|---|---|---|
| 0778 | Swim in Rising Water | Hard |
| 0004 | Median of Two Sorted Arrays | Hard |
| 0033 | Search in Rotated Sorted Array | Medium |
| 0034 | Find First and Last Position of Element in Sorted Array | Medium |
| 0035 | Search Insert Position | Easy |
| 0074 | Search a 2D Matrix | Medium |
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.