Minimum Skips to Arrive at Meeting On Time — LeetCode 1883 Python Solution
- Problem
- #1883
- Pattern
- Dynamic Programming
- Reading time
- 3 min
- Source
- leetcode.com
The problem
You are given an integer hoursBefore, the number of hours you have to travel to your meeting. To arrive at your meeting, you have to travel through n roads.
Example
- Input
- dist = [1,3,2], speed = 4, hoursBefore = 2
- Output
- 1
- Explanation
- Without skipping any rests, you will arrive in (1/4 + 3/4) + (3/4 + 1/4) + (2/4) = 2.5 hours.
Python solution
class Solution:
def minSkips(self, dist: List[int], speed: int, hoursBefore: int) -> int:
n = len(dist)
f = [[inf] * (n + 1) for _ in range(n + 1)]
f[0][0] = 0
eps = 1e-8
for i, x in enumerate(dist, 1):
for j in range(i + 1):
if j < i:
f[i][j] = min(f[i][j], ceil(f[i - 1][j] + x / speed - eps))
if j:
f[i][j] = min(f[i][j], f[i - 1][j - 1] + x / speed)
for j in range(n + 1):
if f[n][j] <= hoursBefore + eps:
return j
return -1Complexity
| Measure | Complexity |
|---|---|
| Time | O(n^2) |
| Space | O(n^2), where n is the number of roads auxiliary |
Pattern: Dynamic Programming
Define a state, write the transition, and stop recomputing the same subproblem. LeetCode 1883. Minimum Skips to Arrive at Meeting On Time is filed here on both counts: the reference solution below belongs to the algorithm family this hub collects, and LeetCode tags it Dynamic Programming.
The dynamic programming guide has the Python template for the pattern and the 481 LeetCode problems that use it.
Related problems
Frequently asked questions
- How hard is LeetCode 1883. Minimum Skips to Arrive at Meeting On Time?
- LeetCode 1883. Minimum Skips to Arrive at Meeting On Time is rated Hard on LeetCode.
- What is the time complexity of LeetCode 1883. Minimum Skips to Arrive at Meeting On Time?
- The Python solution on this page runs in O(n^2).
- What is the space complexity of LeetCode 1883. Minimum Skips to Arrive at Meeting On Time?
- The Python solution on this page uses O(n^2), where n is the number of roads auxiliary space.
- What topics does LeetCode 1883. Minimum Skips to Arrive at Meeting On Time cover?
- LeetCode 1883. Minimum Skips to Arrive at Meeting On Time is tagged Array and Dynamic Programming on LeetCode.