Problem solution · Python

Minimum Cost to Buy Apples II

Minimum Cost to Buy Apples II: 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
86 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 Cost to Buy Apples II, 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

  • 86 lines of Python from the credited upstream file minimum-cost-to-buy-apples-ii.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 Cost to Buy Apples II · PythonPython
Use this to learn the idea, then write your own version.
# Time:  O(n * (n + elogn))# Space: O(n + e) import heapq  # dijkstra's algorithmclass Solution(object):    def minCost(self, n, prices, roads):        """        :type n: int        :type prices: List[int]        :type roads: List[List[int]]        :rtype: List[int]        """        INF = float("inf")        def dijkstra(start, target):            best = [INF]*len(adj)            best[start] = 0            min_heap = [(best[start], start)]            while min_heap:                curr, u = heapq.heappop(min_heap)                if curr != best[u]:                    continue                if u == target:                    return curr                for v, w in adj[u]:                         if best[v] <= curr+w:                        continue                    best[v] = curr+w                    heapq.heappush(min_heap, (best[v], v))            return INF         adj = [[] for _ in xrange(2*n)]        for u, v, c, t in roads:            adj[u].append((v, c))            adj[v].append((u, c))            adj[u+n].append((v+n, c*t))            adj[v+n].append((u+n, c*t))        for i in xrange(n):            adj[i].append((i+n , prices[i]))        return [dijkstra(i, i+n) for i in xrange(n)]  # Time:  O(n * (n + elogn))# Space: O(n + e)import heapq  # dijkstra's algorithmclass Solution2(object):    def minCost(self, n, prices, roads):        """        :type n: int        :type prices: List[int]        :type roads: List[List[int]]        :rtype: List[int]        """        INF = float("inf")        def dijkstra(adj, start):            best = [INF]*len(adj)            best[start] = 0            min_heap = [(best[start], start)]            while min_heap:                curr, u = heapq.heappop(min_heap)                if curr != best[u]:                    continue                for v, w in adj[u]:                         if best[v] <= curr+w:                        continue                    best[v] = curr+w                    heapq.heappush(min_heap, (best[v], v))            return best         adj = [[[] for _ in xrange(n)] for _ in xrange(2)]        for u, v, c, t in roads:            adj[0][u].append((v, c))            adj[0][v].append((u, c))            adj[1][u].append((v, c*t))            adj[1][v].append((u, c*t))        result = [0]*n        for i in xrange(n):            dist = [dijkstra(adj[j], i) for j in xrange(2)]            result[i] = min(dist[0][j]+prices[j]+dist[1][j] for j in xrange(n))        return result 

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 ↗