Solution: Connecting 'n' Pipes with Minimum Cost
This review provides a detailed analysis of the solution to connect “n” pipes for the minimum cost.
We'll cover the following...
Solution #1: Sorting
Press + to interact
class MinimumCost {public static int minCost(int[] pipes) {int cost = 0;int n = pipes.length;for (int i = 0; i < n - 1; i++) {Arrays.sort(pipes); //Sorting the arrayint prev_cost = cost; // store previous cost for later usecost = (pipes[i] + pipes[i + 1]); //find current costpipes[i + 1] = cost; //insert in arraycost = cost + prev_cost; //add with previous cost}return cost;}}class Main{public static void main(String[] args) {int[] pipes = {4, 3, 2, 6 };System.out.println("Total cost for connecting pipes is " + MinimumCost.minCost(pipes));int[] pipes1 = {1, 1, 2, 6};System.out.println("Total cost for connecting pipes1 is " + MinimumCost.minCost(pipes1));}}
Explanation
-
Start by sorting the
pipes
array, shown in line 9. -
Next, find the
cost
of connecting two adjacent pipes by summing the cost at the current index and the next index of thepipes
array (line 10). -
Insert this cost into the array (line 11).
-
Next, update the cost by adding it to the previously ...
Access this course and 1400+ top-rated courses and projects.