Solution: Connecting n Pipes With Minimum Cost
This review provides a detailed analysis of how to connect n pipes with the minimum cost.
We'll cover the following...
Solution: sorting
Explanation
If you look at the animation present in the previous lesson, you will notice that the lengths of the pipes which are picked first are included iteratively (i.e. each time). Therefore, we want them to be as small as possible. Now, let’s be greedy!
First, we initialize the priority queue with the pipes. The priority queue ensures that the two smallest length pipes are selected in every iteration. In this way, in every iteration, the previous cost (which is the length of the last two pipes connected) is added to the cost of connected pipes in this iteration until all pipes are connected.
Time complexity
The time complexity for this solution is because both the push and pop operations of the priority queue take O(logn) time.