Minimum Cost to Buy Apples — LeetCode 2473 Python Solution

MediumLeetCode PremiumGraphArrayShortest PathHeap (Priority Queue)
Problem
#2473
Reading time
5 min

The problem

You are given a positive integer n representing n cities numbered from 1 to n. You are also given a 2D array roads, where roads[i] = [ai, bi, costi] indicates that there is a bidirectional road between cities ai and bi with a cost of traveling equal to costi.

Example

Input
n = 4, roads = [[1,2,4],[2,3,2],[2,4,5],[3,4,1],[1,3,4]], appleCost = [56,42,102,301], k = 2
Output
[54,42,48,51]
Explanation
The minimum cost for each starting city is the following:

Python solution

Python
class Solution:
    def minCost(
        self, n: int, roads: List[List[int]], appleCost: List[int], k: int
    ) -> List[int]:
        def dijkstra(i):
            q = [(0, i)]
            dist = [inf] * n
            dist[i] = 0
            ans = inf
            while q:
                d, u = heappop(q)
                ans = min(ans, appleCost[u] + d * (k + 1))
                for v, w in g[u]:
                    if dist[v] > dist[u] + w:
                        dist[v] = dist[u] + w
                        heappush(q, (dist[v], v))
            return ans

        g = defaultdict(list)
        for a, b, c in roads:
            a, b = a - 1, b - 1
            g[a].append((b, c))
            g[b].append((a, c))
        return [dijkstra(i) for i in range(n)]

Complexity

MeasureComplexity
TimeO(n \times m \times \log m), where n and m are the number of cities and roads, respectively
SpaceO(n) auxiliary

Pattern: Heap / Priority Queue

Keep only the best k elements, or always pull the smallest, in log time. LeetCode 2473. Minimum Cost to Buy Apples is filed here on both counts: the reference solution below belongs to the algorithm family this hub collects, and LeetCode tags it Heap (Priority Queue).

The heap / priority queue guide has the Python template for the pattern and the 163 LeetCode problems that use it.

Related problems

Frequently asked questions

How hard is LeetCode 2473. Minimum Cost to Buy Apples?
LeetCode 2473. Minimum Cost to Buy Apples is rated Medium on LeetCode.
What is the time complexity of LeetCode 2473. Minimum Cost to Buy Apples?
The Python solution on this page runs in O(n \times m \times \log m), where n and m are the number of cities and roads, respectively.
What is the space complexity of LeetCode 2473. Minimum Cost to Buy Apples?
The Python solution on this page uses O(n) auxiliary space.
What topics does LeetCode 2473. Minimum Cost to Buy Apples cover?
LeetCode 2473. Minimum Cost to Buy Apples is tagged Graph, Array, Shortest Path and Heap (Priority Queue) on LeetCode.
Is LeetCode 2473. Minimum Cost to Buy Apples a premium problem?
Yes. LeetCode 2473. Minimum Cost to Buy Apples is a LeetCode Premium problem, so the full statement and test cases require a paid LeetCode subscription.

Stuck on problems like this in a live interview?

Stealth Interview is a desktop app for macOS and Windows. It reads the problem off your screen and returns a working solution with a step-by-step explanation and its time and space complexity — invisible to screen sharing.

Get Stealth Interview