Problem solution · Python

Minimum Time to Reach Target with Limited Power

Minimum Time to Reach Target with Limited Power: a Python solution using heap or priority queue. Learn the idea, check the complexity, and read the full code, with credit to Kamyu LeetCode Solutions.

Technique
Heap or priority queue
Source
Kamyu LeetCode Solutions
Length
41 lines
Start with the idea.

Try the problem first. If you get stuck, read the approach below, then write your own solution. The full code is at the bottom.

Approach

Heap or priority queue

For Minimum Time to Reach Target with Limited Power, the implementation repeatedly takes the currently best candidate from a heap while inserting newly available choices.

  1. Define the priority key and whether the smallest or largest item should lead.
  2. Push each candidate when it becomes eligible.
  3. Discard stale entries when necessary and process the best live candidate.

Code notes

  • 41 lines of Python from the credited upstream file minimum-time-to-reach-target-with-limited-power.py.
  • The implementation visibly relies on sequence storage, work queue.
  • No explicit loop blocks detected.

Complexity

Count heap pushes and pops; each normally contributes a logarithmic factor in the heap size.

Check the problem constraints before deciding whether this complexity will pass.

Source

Code and credit

This code comes from Kamyu LeetCode Solutions by kamyu104 and is used under the MIT licence.

Full codeMinimum Time to Reach Target with Limited Power · PythonPython
Use this to learn the idea, then write your own version.
# Time:  O((n * p + e * p) * log(n * p))# Space: O(n * p) import heapq  # dijkstra's algorithmclass Solution(object):    def minTimeMaxPower(self, n, edges, power, cost, source, target):        """        :type n: int        :type edges: List[List[int]]        :type power: int        :type cost: List[int]        :type source: int        :type target: int        :rtype: List[int]        """        adj = [[] for _ in xrange(n)]        for u, v, w in edges:            adj[u].append((v, w))        dist = [[float("inf")]*(power+1) for _ in xrange(n)]        dist[source][power] = 0        min_heap = [(dist[source][power] , -power, source)]        while min_heap:            t, p, u = heapq.heappop(min_heap)            p = -p            if t > dist[u][p]:                continue            if u == target:                return [t, p]            np = p-cost[u]            if np < 0:                continue            for v, w in adj[u]:                if t+w >= dist[v][np]:                    continue                dist[v][np] = t+w                heapq.heappush(min_heap, (dist[v][np], -np, v))        return [-1, -1] 

Did this explanation save you time? I'm a Grade 11 student building this free library to make difficult algorithms easier to understand.

Buy me a coffee ↗