In the Minimum Cost to Buy Apples problem, you are given a set of cities connected by roads with specific travel costs. Each city also has a price for an apple. You want to find, for each city i, the minimum cost to start at i, travel to any city j (including i), buy an apple at city j, and return to city i. The travel cost is usually multiplied by a constant (like 2 for a round trip).
This Minimum Cost to Buy Apples interview question is seen at companies like Media.net and Directi. It is a multi-source shortest path problem. It tests if a candidate can adapt Dijkstra's Algorithm to handle multiple possible "targets" (apple sources) simultaneously or use a "super-node" trick.
The Multi-Source Dijkstra interview pattern is the most efficient.
i with an edge weight equal to the apple_cost[i].i in this graph will be the minimum cost to buy an apple and "get to" city i.i to j, the road weights in your graph should be 2 * travel_cost.City 1: apple=10. City 2: apple=5. Road 1-2: cost 2.
2 * 2 = 4.cost = 10.travel(1->2) + apple(2) + travel(2->1) = 2 + 5 + 2 = 9.The "Super-Source" or "Virtual Node" is a common trick in Graph interview patterns. If you have multiple starting points or multiple potential destinations and want the "closest" one, try connecting them all to a single virtual node with zero or cost-based weights.
| Title | Difficulty | Topics | LeetCode |
|---|---|---|---|
| Minimum Cost of a Path With Special Roads | Medium | Solve | |
| Path with Maximum Probability | Medium | Solve | |
| Find Minimum Time to Reach Last Room I | Medium | Solve | |
| Find Minimum Time to Reach Last Room II | Medium | Solve | |
| Minimum Cost Path with Edge Reversals | Medium | Solve |