This is a premium problem. We're working on making it available for free soon.
Use these hints if you're stuck. Try solving on your own first.
Notice that the path you take to buy an apple will be the same path to return to the starting city.
Starting from each city, use Dijkstra’s algorithm to find the best city to travel to.
Solutions for this premium problem will be available for free soon.
Browse Free ProblemsWatch expert explanations and walkthroughs
Practice problems asked by these companies to ace your technical interviews.
Explore More ProblemsJot down your thoughts, approach, and key learnings
Dijkstra’s algorithm is ideal because the cities and roads form a weighted graph with non-negative edge costs. It helps compute the shortest travel costs from potential apple-buying cities to all others efficiently.
Graph problems involving shortest paths and priority queues are common in FAANG-style interviews. While this exact problem may not always appear, similar variations testing Dijkstra and graph optimization frequently do.
A priority queue (min-heap) is the most suitable data structure. It allows efficient extraction of the current minimum cost city during Dijkstra’s traversal while updating distances across the graph.
The optimal approach uses a multi-source Dijkstra algorithm. Each city starts with its apple price as the initial cost, and edges are scaled by the travel factor. This efficiently computes the minimum total cost to buy and return an apple for every city.